-
Notifications
You must be signed in to change notification settings - Fork 16
feat/TE-29132-Added already present addons to rest api application #210
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat/TE-29132-Added already present addons to rest api application #210
Conversation
WalkthroughAdds new modules and actions for MSSQL, MySQL, SQL Server, REST utilities, substring manipulation, and XML comparison. Introduces multiple REST/Web actions to execute queries, validate results, compare outputs, store results in runtime variables, and enhanced XML diffing. Updates several POMs (versions/dependencies), and adds utility classes and properties. Changes
Sequence Diagram(s)sequenceDiagram
participant Test as Test Step
participant Action as DB Action
participant DB as Database
participant RT as RunTimeData
Test->>Action: Provide Query, DB_Connection_URL, variable-name
Action->>DB: Open JDBC Connection
Action->>DB: Execute SELECT
DB-->>Action: ResultSet (rows)
Action->>Action: Build result (first cell or CSV)
Action->>RT: Set key/value (optional)
Action-->>Test: Result (SUCCESS/FAILED) + message
sequenceDiagram
participant Test as Test Step
participant Action as Compare Queries
participant DB as Database
Test->>Action: Provide Query1, Query2, DB_Connection_URL
Action->>DB: Conn A, Exec Query1 -> RS1
Action->>DB: Conn B, Exec Query2 -> RS2
Action->>Action: Compare metadata (columns)
Action->>Action: Compare data (rows/values)
Action-->>Test: SUCCESS if equal else FAILED with diffs
sequenceDiagram
participant Test as Test Step
participant XMLAct as Compare XML
participant Util as XMLUtility
Test->>XMLAct: filepath1, filepath2, X-Paths
XMLAct->>Util: urlToFileConverter(file1/file2)
XMLAct->>Util: parseXMLWithLineNumbers
XMLAct->>Util: findDifferencesWithIgnore(..., ignoredPaths)
Util-->>XMLAct: Differences list
XMLAct-->>Test: SUCCESS if none else FAILED + summary
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 104
🔭 Outside diff range comments (3)
sql_server_queries/pom.xml (1)
72-85: Upgrade JDBC driver & remove deprecated ADAL4J
- File: sql_server_queries/pom.xml (lines 72–85)
- Update the Microsoft JDBC Driver for SQL Server to the latest Java 11–compatible GA release.
- Remove the ADAL4J dependency (com.microsoft.azure:adal4j), since it’s officially deprecated—rely solely on MSAL4J and follow the Microsoft migration guide.
Suggested diff:
--- sql_server_queries/pom.xml @@ lines 72–85 - <dependency> - <groupId>com.microsoft.sqlserver</groupId> - <artifactId>mssql-jdbc</artifactId> - <version>10.2.0.jre11</version> - </dependency> + <dependency> + <groupId>com.microsoft.sqlserver</groupId> + <artifactId>mssql-jdbc</artifactId> + <version>12.10.1.jre11</version> + </dependency> <dependency> <groupId>com.microsoft.azure</groupId> <artifactId>msal4j</artifactId> <version>1.11.2</version> </dependency> - <dependency> - <groupId>com.microsoft.azure</groupId> - <artifactId>adal4j</artifactId> - <version>1.6.5</version> - </dependency>xml_verification_/pom.xml (1)
20-21: Inconsistent Lombok version management; fix property and use it in dependency.The properties block sets lombok.version to 1.18.20 while the dependency hardcodes 1.18.30. Align by setting the property to 1.18.30 and reference it in the dependency.
- <lombok.version>1.18.20</lombok.version> + <lombok.version>1.18.30</lombok.version> @@ - <dependency> - <groupId>org.projectlombok</groupId> - <artifactId>lombok</artifactId> - <version>1.18.30</version> - <optional>true</optional> - </dependency> + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <version>${lombok.version}</version> + <optional>true</optional> + </dependency>Also applies to: 31-35
xml_verification_/src/main/java/com/testsigma/addons/web/CompareLocalXMLFiles.java (1)
73-84: Redundant temporary file creation and potential resource leakThe code creates temporary files on lines 73-76 but then immediately overwrites them with the result from
urlToFileConverteron lines 79-80. This creates unnecessary files that may not be deleted.-// 2. Convert URLs/Paths to Temporary Files -baseFile = File.createTempFile("baseXml_", ".xml"); -actualFile = File.createTempFile("actualXml_", ".xml"); -logger.info("Created temporary base file: " + baseFile.getAbsolutePath()); -logger.info("Created temporary actual file: " + actualFile.getAbsolutePath()); - -// Use the utility to handle potential URLs or local paths -baseFile = xmlUtility.urlToFileConverter(filePath1); -actualFile = xmlUtility.urlToFileConverter(filePath2); -logger.info("Prepared base & actual file content."); +// 2. Convert URLs/Paths to Temporary Files +// Use the utility to handle potential URLs or local paths +baseFile = xmlUtility.urlToFileConverter(filePath1); +actualFile = xmlUtility.urlToFileConverter(filePath2); +logger.info("Prepared base file: " + baseFile.getAbsolutePath()); +logger.info("Prepared actual file: " + actualFile.getAbsolutePath());
♻️ Duplicate comments (1)
mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlselectandstore.java (1)
43-51: Thread-safety concern with global proxy settings manipulationSimilar to MysqlqueriesValidate, this code modifies JVM-wide proxy settings which is not thread-safe and could affect other concurrent operations.
#!/bin/bash # Count how many MySQL actions manipulate proxy settings to understand the pattern rg -l "nonProxyHosts" mysql_queries/src/ | wc -l # Check if there's a common base class that could handle this ast-grep --pattern 'class $_ extends RestApiAction { $$$ }' mysql_queries/src/Also applies to: 77-85
🧹 Nitpick comments (60)
rest_api_utils/pom.xml (3)
67-67: Nit: finalName duplicates artifactId.Unless you plan to produce differently named artifacts per profile, you can omit . Maven will default to artifactId-version.
24-35: General dependency hygiene: avoid mixing multiple test frameworks unless necessary.You currently pull both JUnit 5 and TestNG. If both are truly needed, configure surefire accordingly; otherwise, prefer one to reduce surface area and transitive conflicts.
I can generate a surefire configuration tailored to your chosen framework and update this POM accordingly.
Also applies to: 37-41
12-22: Clean up properties and avoid pre-release JUnit; consider adding a Jackson version property.
- junit.jupiter.version points to a milestone (5.8.0-M1). Use a stable GA release.
- testsigma.addon.maven.plugin property is defined but unused.
- Consider centralizing jackson version in a property to ease coordinated upgrades.
Suggested changes:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> <testsigma.sdk.version>1.2.24_cloud</testsigma.sdk.version> - <junit.jupiter.version>5.8.0-M1</junit.jupiter.version> - <testsigma.addon.maven.plugin>1.0.0</testsigma.addon.maven.plugin> + <junit.jupiter.version>5.11.3</junit.jupiter.version> + <jackson.version>2.17.2</jackson.version> <maven.source.plugin.version>3.2.1</maven.source.plugin.version> <lombok.version>1.18.30</lombok.version> </properties>Please verify the exact latest stable versions you intend to use. Run this to check current releases:
#!/bin/bash # Verify stable versions for junit and jackson curl -s 'https://search.maven.org/solrsearch/select?q=g:%22org.junit.jupiter%22+AND+a:%22junit-jupiter-bom%22&rows=1&wt=json' | jq -r '.response.docs[0].latestVersion' curl -s 'https://search.maven.org/solrsearch/select?q=g:%22com.fasterxml.jackson%22+AND+a:%22jackson-bom%22&rows=1&wt=json' | jq -r '.response.docs[0].latestVersion'rest_api_utils/src/main/java/com/testsigma/addons/restapi/CheckIfContains.java (1)
8-8: Remove unused importThe
NoSuchElementExceptionfrom Selenium is imported but never thrown by this REST API action.-import org.openqa.selenium.NoSuchElementException;rest_api_utils/src/main/java/com/testsigma/addons/restapi/StoreTestDataParameterIntoRuntimeVariable.java (3)
6-6: Remove unused importThe
WebActionimport is not needed for this REST API action.-import com.testsigma.sdk.WebAction;
11-11: Remove unused importThe
NoSuchElementExceptionfrom Selenium is imported but never thrown by this REST API action.-import org.openqa.selenium.NoSuchElementException;
20-20: Remove unused constantThe
ERROR_MESSAGEconstant is defined but never used in the execute method.- private static final String ERROR_MESSAGE = "Expected textarea Not Found";rest_api_utils/src/main/java/com/testsigma/addons/restapi/CheckIfEmpty.java (2)
7-7: Remove unused importThe
NoSuchElementExceptionfrom Selenium is imported but never thrown by this REST API action.-import org.openqa.selenium.NoSuchElementException;
21-21: Remove unnecessary exception declarationThe method doesn't throw
NoSuchElementException, so it shouldn't be declared.- public Result execute() throws NoSuchElementException { + public Result execute() {rest_api_utils/src/main/java/com/testsigma/addons/restapi/ToCompare.java (4)
7-7: Remove unused importThe
NoSuchElementExceptionfrom Selenium is imported but never thrown by this REST API action.-import org.openqa.selenium.NoSuchElementException;
28-28: Remove unnecessary exception declarationThe method doesn't throw
NoSuchElementException, so it shouldn't be declared.- public Result execute() throws NoSuchElementException { + public Result execute() {
33-45: Simplify logic and remove redundant default caseThe operator comparison logic can be simplified, and the empty else block at line 43-45 is redundant since
returnResultis already initialized toResult.FAILED.Result returnResult = Result.FAILED; - if(operatorString.equals(">")) { + switch (operatorString) { + case ">": returnResult = testDataString1.compareTo(testDataString2) > 0 ? Result.SUCCESS : Result.FAILED; - } else if(operatorString.equals("<")){ + break; + case "<": returnResult = testDataString1.compareTo(testDataString2) < 0 ? Result.SUCCESS : Result.FAILED; - } else if(operatorString.equals(">=")) { + break; + case ">=": returnResult = testDataString1.equals(testDataString2) || testDataString1.compareTo(testDataString2) > 0 ? Result.SUCCESS : Result.FAILED; - } else if(operatorString.equals("<=")){ + break; + case "<=": returnResult = testDataString1.equals(testDataString2) || testDataString1.compareTo(testDataString2) < 0 ? Result.SUCCESS : Result.FAILED; - } else if(operatorString.equals("==")){ + break; + case "==": returnResult = testDataString1.equals(testDataString2) ? Result.SUCCESS : Result.FAILED; - } else { - returnResult = Result.FAILED; + break; + default: + setErrorMessage("Invalid operator: " + operatorString); + return Result.FAILED; }
38-40: Optimize >= and <= comparison logicThe >= and <= comparisons can be simplified using
compareTo() >= 0andcompareTo() <= 0respectively.- returnResult = testDataString1.equals(testDataString2) || testDataString1.compareTo(testDataString2) > 0 ? Result.SUCCESS : Result.FAILED; + returnResult = testDataString1.compareTo(testDataString2) >= 0 ? Result.SUCCESS : Result.FAILED; } else if(operatorString.equals("<=")){ - returnResult = testDataString1.equals(testDataString2) || testDataString1.compareTo(testDataString2) < 0 ? Result.SUCCESS : Result.FAILED; + returnResult = testDataString1.compareTo(testDataString2) <= 0 ? Result.SUCCESS : Result.FAILED;mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlutil.java (1)
1-5: Empty utility class; either implement, prevent instantiation, or remove.This empty class adds maintenance noise and can confuse consumers. If it’s a placeholder, make it non-instantiable; otherwise, remove it until needed. Also consider standard Java naming (MysqlUtil).
Minimal hardening:
-package com.testsigma.addons.restapi; - -public class Mysqlutil { - -} +package com.testsigma.addons.restapi; + +/** + * Placeholder for MySQL REST API utilities. Add methods when needed. + */ +public final class Mysqlutil { + private Mysqlutil() { /* prevent instantiation */ } +}Also note there is another Mysqlutil in package com.testsigma.addons.web. Consider consolidating to avoid duplicated names across packages.
Check if this class is referenced anywhere; if unused, delete it:
#!/bin/bash set -euo pipefail echo "Searching for references to com.testsigma.addons.restapi.Mysqlutil..." rg -n --no-ignore -S '\bMysqlutil\b|com\.testsigma\.addons\.restapi\.Mysqlutil'mssqldb_queries/src/main/java/com/testsigma/addons/mssqldb/util/DatabaseUtil.java (1)
6-11: Remove unused imports.Several imports (
ResultSet,Statement,NoSuchElementException,Result) are not used in this utility class.import java.sql.Connection; import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.Statement; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.openqa.selenium.NoSuchElementException; - -import com.testsigma.sdk.Result;sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlupdatequeriesWithUrl.java (2)
7-7: Remove unused import.The
WebActionimport is not used in this class.-import com.testsigma.sdk.WebAction;
29-29: Initialize StringBuffer only when needed.The StringBuffer is initialized as an instance variable but could be declared locally within the try block where it's used, improving memory efficiency and code clarity.
- StringBuffer sb = new StringBuffer();And initialize it locally:
try{ + StringBuffer sb = new StringBuffer(); connection = databaseUtil.getConnection(url);mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlupdatequeries.java (1)
7-7: Remove unused import.The
WebActionimport is not used in this class.-import com.testsigma.sdk.WebAction;sql_server_queries/src/main/java/com/testsigma/addons/restapi/Sqlupdatequeries.java (1)
7-7: Remove unused import.The
WebActionimport is not used in this class.-import com.testsigma.sdk.WebAction;xml_verification_/src/main/java/com/testsigma/addons/restapi/ExtractTheContentOfXML.java (2)
6-6: Remove unused import.The
WebActionimport is not used in this class.-import com.testsigma.sdk.WebAction;
48-50: Consider using String response handler for simpler implementation.Since you're reading all bytes to a String anyway, using
HttpResponse.BodyHandlers.ofString()would be simpler and eliminate the need for manual resource management.- HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); - - String xmlContent = new String(response.body().readAllBytes(), StandardCharsets.UTF_8); + HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); + String xmlContent = response.body();sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlselectWithUrl.java (1)
7-7: Remove unused import.The
WebActionimport is not used in this class.-import com.testsigma.sdk.WebAction;substring_removebylength/src/main/java/com/testsigma/addons/restapi/RemovePositions.java (2)
14-17: Fix typos in the action annotation.Multiple grammatical and spelling errors in the description field.
-description = "THis action removes the no of first,last position of given string and store into a varaible", +description = "This action removes the specified number of first and last positions from a given string and stores the result into a variable",
45-46: Fix misleading success message.The message mentions "first and last letters" but the action actually removes a specified number of positions, not just letters.
- setSuccessMessage("String after removing first and last letters:" + resultstring +":is stored in the runtime variable:" +testData3.getValue().toString()); - logger.info("String after removing first and last letters:" + resultstring +":is stored in the runtime variable:" +testData3.getValue().toString()); + setSuccessMessage("String after removing " + firstPos + " characters from start and " + lastPos + " characters from end: " + resultstring + " is stored in runtime variable: " + testData3.getValue().toString()); + logger.info("String after removing " + firstPos + " characters from start and " + lastPos + " characters from end: " + resultstring + " is stored in runtime variable: " + testData3.getValue().toString());sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlqueriesValidateWithUrl.java (1)
51-51: Remove unnecessary getObject call in row counting.Line 51 calls
resultSet.getObject(1).toString()but doesn't use the result, which is inefficient.while (resultSet.next()){ - resultSet.getObject(1).toString(); rowsUpdatedOrFetched ++; }mssqldb_queries/src/main/java/com/testsigma/addons/web/MSSqlStoreselect.java (1)
20-20: Action text doesn't specify authentication requirementsThe action text should mention that authentication parameters are required as part of the DB_Connection_URL, similar to how the Sqlselect action explicitly mentions username and password.
-@Action(actionText = "Execute MSSqlDB Select-Query on the connection DB_Connection_URL and store output into a variable-name", +@Action(actionText = "Execute MSSqlDB Select-Query on the connection DB_Connection_URL (including authentication) and store output into a variable-name",xml_verification_/src/main/java/com/testsigma/addons/utilities/XMLUtility.java (3)
3-4: Remove unnecessary commentThe comment about adding imports is not needed as the imports are already present.
-// Add these imports to your existing XMLUtility imports -
448-449: Consider reducing log level for expected scenariosUsing
logger.warn()for a fallback case that "should technically be found" might be too noisy in production logs if this occurs frequently.-logger.warn("Could not definitively determine node index for: " + getXPath(node) + ". Returning calculated index: " + index); +logger.debug("Could not definitively determine node index for: " + getXPath(node) + ". Returning calculated index: " + index);
513-514: Avoid logging sensitive locator unavailability at WARN levelIf the locator is frequently unavailable for certain XML structures, this warning could flood the logs.
-logger.warn("DOM Builder: Locator not available for element " + qName + ", line numbers will be missing."); +logger.debug("DOM Builder: Locator not available for element " + qName + ", line numbers will be missing.");mssqldb_queries/src/main/java/com/testsigma/addons/restapi/MSSqlselect.java (1)
53-54: Simplify null handling logicWhen
resultSet.wasNull()returns true, appending an empty string is redundant.-if (resultSet.wasNull()) { - sb.append(""); -} -sb.append(columnValue); +if (!resultSet.wasNull()) { + sb.append(columnValue); +}mysql_queries/src/main/java/com/testsigma/addons/restapi/MysqlCallProcedure.java (1)
63-65: Simplify null handling logicThe null check and empty string append is redundant.
-if (resultSet.wasNull()) { - sb.append(""); -} -sb.append(columnValue); +if (!resultSet.wasNull()) { + sb.append(columnValue); +}mssqldb_queries/src/main/java/com/testsigma/addons/web/MsSqlSelectAndroid.java (1)
53-55: Simplify null handling logicAppending an empty string when null is redundant.
-if (resultSet.wasNull()) { - sb.append(""); -} -sb.append(columnValue); +if (!resultSet.wasNull()) { + sb.append(columnValue); +}sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlqueriesValidate.java (1)
7-7: Remove unused WebAction importThe
WebActionimport is not used in this REST API action class.-import com.testsigma.sdk.WebAction;sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlselectvalidateWithUrl.java (2)
7-7: Remove unused WebAction importThe
WebActionimport is not used in this REST API action class.-import com.testsigma.sdk.WebAction;
60-60: Fix grammatical error in error messageThe error message has a grammatical issue.
-sb.append("The selected query value not match with expected rows:" + "<br>"); +sb.append("The selected query value does not match with expected value:" + "<br>");mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlselect.java (1)
7-7: Remove unused WebAction importThe
WebActionimport is not used in this REST API action class.-import com.testsigma.sdk.WebAction;xml_verification_/src/main/java/com/testsigma/addons/restapi/CompareXMLTextsIgnoringXPaths.java (4)
7-7: Remove unused WebAction importThe
WebActionimport is not used in this REST API action class.-import com.testsigma.sdk.WebAction;
45-46: Misleading variable namesThe variables
filePath1andfilePath2are misleading as they contain XML content, not file paths.-String filePath1 = testData1.getValue().toString(); -String filePath2 = testData2.getValue().toString(); +String xmlContent1 = testData1.getValue().toString(); +String xmlContent2 = testData2.getValue().toString();And update the subsequent usage:
-Document doc1 = parseXML(filePath1); -Document doc2 = parseXML(filePath2); +Document doc1 = parseXML(xmlContent1); +Document doc2 = parseXML(xmlContent2);
61-61: Fix log message typoThe log message incorrectly states "parsing xPaths" instead of "ignoring xPaths".
-logger.info("Text2 after parsing xPaths " + doc2); +logger.info("Text2 after ignoring xPaths " + doc2);
54-54: Handle empty XPath input gracefullyThe code doesn't handle the case where the XPath input is empty or contains only whitespace.
-String[] xpathArray = xPathsToIgnore.split(","); +String[] xpathArray = xPathsToIgnore.trim().isEmpty() ? new String[0] : xPathsToIgnore.split(",");mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlselectvalidate.java (2)
7-7: Remove unused import.The
WebActionimport is not used in this class as it extendsRestApiAction.-import com.testsigma.sdk.WebAction;
20-20: Fix typo in action description."aginst" should be "against" in the action description.
-description = "This Action executes a given Select Query and validates the result(First cell data) aginst the expected value.", +description = "This Action executes a given Select Query and validates the result(First cell data) against the expected value.",mysql_queries/src/main/java/com/testsigma/addons/restapi/MysqlCreateProcedure.java (1)
7-7: Remove unused import.The
WebActionimport is not used in this class.-import com.testsigma.sdk.WebAction;sql_server_queries/src/main/java/com/testsigma/addons/restapi/Sqlselectvalidate.java (2)
7-7: Remove unused import.The
WebActionimport is not used in this class.-import com.testsigma.sdk.WebAction;
21-21: Fix typo in action description."aginst" should be "against" in the action description.
-description = "This Action executes a given Select Query and validates the result(First cell data) aginst the expected value.", +description = "This Action executes a given Select Query and validates the result(First cell data) against the expected value.",mssqldb_queries/src/main/java/com/testsigma/addons/web/MsSqlSelectIOS.java (1)
40-41: Redundant call to getMetaData().Line 41 calls
resultSet.getMetaData().getColumnCount()whenrsmd(Line 40) already contains the metadata and should be reused for efficiency.ResultSetMetaData rsmd = resultSet.getMetaData(); - int columnNo = resultSet.getMetaData().getColumnCount(); + int columnNo = rsmd.getColumnCount();sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlqueriesWithUrl.java (2)
7-7: Remove unused importThe
WebActionimport is not used in this REST API action class.-import com.testsigma.sdk.WebAction;
56-56: Simplify empty string append logicWhen
resultSet.wasNull()returns true, appending an empty string is redundant since it doesn't change the buffer.- if (resultSet.wasNull()) { - sb.append(""); - } + // Skip null values - no need to append empty stringmysql_queries/src/main/java/com/testsigma/addons/restapi/MysqlValidateQueriesonDatabases.java (1)
7-7: Remove unused importThe
WebActionimport is not used in this REST API action class.-import com.testsigma.sdk.WebAction;mssqldb_queries/src/main/java/com/testsigma/addons/web/MSSqlselect.java (1)
54-54: Simplify empty string append logicAppending an empty string when
resultSet.wasNull()is true doesn't change the buffer content.- if (resultSet.wasNull()) { - sb.append(""); - } + // Skip null values - no need to append empty stringmssqldb_queries/src/main/java/com/testsigma/addons/restapi/MSSqlValidate.java (1)
7-7: Remove unused importThe
WebActionimport is not used in this REST API action class.-import com.testsigma.sdk.WebAction;sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlValidateQueriesonTablesWithUrl.java (3)
7-7: Remove unused importThe
WebActionimport is not used in this REST API action class.-import com.testsigma.sdk.WebAction;
100-100: Fix typo in success messageThe success message contains a grammatical error ("are have").
-setSuccessMessage("The two queries are have similar data"); +setSuccessMessage("The two queries have similar data");
61-67: Return result consistently instead of direct returnsDirect returns from within the try block could bypass important cleanup or logging that might be added later.
Consider setting the result and breaking out of the validation flow:
boolean metadataComparisonSuccess = compareMetadata(resultSet1,resultSet2); if(!metadataComparisonSuccess) { - return Result.FAILED; + result = Result.FAILED; } -boolean dataComparisonSuccess = compareQueryData(resultSet1, resultSet2); -if(!dataComparisonSuccess) { - return Result.FAILED; +else { + boolean dataComparisonSuccess = compareQueryData(resultSet1, resultSet2); + if(!dataComparisonSuccess) { + result = Result.FAILED; + } } -logger.info(sb.toString()); +if (result == Result.SUCCESS) { + logger.info(sb.toString()); +}mysql_queries/src/main/java/com/testsigma/addons/restapi/MysqlValidateQueriesonTables.java (2)
8-8: Remove unused importWebActionThe
WebActionimport is not used in this REST API action class.-import com.testsigma.sdk.WebAction;
83-84: Fix grammatical error in success messageThe success message contains a grammatical error: "are have" should be "have".
-setSuccessMessage("The two queries are have similar data"); -logger.info("The two queries are have similar data"); +setSuccessMessage("The two queries have similar data"); +logger.info("The two queries have similar data");sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlValidateQueriesonTables.java (4)
7-7: Remove unused importWebActionThe
WebActionimport is not used in this REST API action class.-import com.testsigma.sdk.WebAction;
105-106: Fix grammatical error in success messageThe success message contains a grammatical error: "are have" should be "have".
-setSuccessMessage("The two queries are have similar data"); -logger.info("The two queries are have similar data"); +setSuccessMessage("The two queries have similar data"); +logger.info("The two queries have similar data");
107-107: Redundant logging of StringBufferThe StringBuffer content is logged again after already being logged at line 73. This appears redundant since
sbonly contains comparison data which would have been populated during failed comparisons.Remove the redundant logging:
-logger.info(sb.toString());
163-189: Performance concern: Success logging iterates through entire result sets againWhen the comparison succeeds, the code iterates through both entire result sets again just for logging. For large result sets, this doubles the processing time and memory usage (since CachedRowSets store all data in memory).
Consider making this verbose logging conditional or limiting it to a reasonable number of rows:
// Log the contents of both queries when values match +final int MAX_LOG_ROWS = 10; StringBuilder successLog = new StringBuilder("Values match for all columns. Contents of both queries:\n"); cachedResultSet1.beforeFirst(); cachedResultSet2.beforeFirst(); // Log the contents of cachedResultSet1 successLog.append("Query-1:\n"); +int rowCount = 0; while (cachedResultSet1.next()) { + if (++rowCount > MAX_LOG_ROWS) { + successLog.append("... (truncated, showing first ").append(MAX_LOG_ROWS).append(" rows)\n"); + break; + } successLog.append(cachedResultSet1.getRow()).append(": "); for (int i = 1; i <= columnNo1; i++) { successLog.append(cachedResultSet1.getObject(i)).append("\n"); } successLog.append("\n"); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (55)
mssqldb_queries/pom.xml(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/mssqldb/util/DatabaseUtil.java(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/restapi/MSSqlStoreselect.java(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/restapi/MSSqlValidate.java(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/restapi/MSSqlselect.java(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/web/MSSqlStoreselect.java(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/web/MSSqlValidate.java(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/web/MSSqlValidateAndroids.java(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/web/MSSqlValidateIOS.java(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/web/MSSqlselect.java(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/web/MsSqlSelectAndroid.java(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/web/MsSqlSelectIOS.java(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/web/MsSqlStoreSelectAndroid.java(1 hunks)mssqldb_queries/src/main/java/com/testsigma/addons/web/MsSqlStoreSelectIOS.java(1 hunks)mssqldb_queries/src/main/resources/testsigma-sdk.properties(1 hunks)mysql_queries/pom.xml(2 hunks)mysql_queries/src/main/java/com/testsigma/addons/restapi/MysqlCallProcedure.java(1 hunks)mysql_queries/src/main/java/com/testsigma/addons/restapi/MysqlCreateProcedure.java(1 hunks)mysql_queries/src/main/java/com/testsigma/addons/restapi/MysqlValidateQueriesonDatabases.java(1 hunks)mysql_queries/src/main/java/com/testsigma/addons/restapi/MysqlValidateQueriesonTables.java(1 hunks)mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlqueries.java(1 hunks)mysql_queries/src/main/java/com/testsigma/addons/restapi/MysqlqueriesValidate.java(1 hunks)mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlscriptfile.java(1 hunks)mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlselect.java(1 hunks)mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlselectandstore.java(1 hunks)mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlselectvalidate.java(1 hunks)mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlupdatequeries.java(1 hunks)mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlutil.java(1 hunks)rest_api_utils/pom.xml(1 hunks)rest_api_utils/src/main/java/com/testsigma/addons/restapi/CheckIfContains.java(1 hunks)rest_api_utils/src/main/java/com/testsigma/addons/restapi/CheckIfEmpty.java(1 hunks)rest_api_utils/src/main/java/com/testsigma/addons/restapi/StoreTestDataParameterIntoRuntimeVariable.java(1 hunks)rest_api_utils/src/main/java/com/testsigma/addons/restapi/ToCompare.java(1 hunks)rest_api_utils/src/main/resources/testsigma-sdk.properties(1 hunks)sql_server_queries/pom.xml(2 hunks)sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlValidateQueriesonTables.java(1 hunks)sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlValidateQueriesonTablesWithUrl.java(1 hunks)sql_server_queries/src/main/java/com/testsigma/addons/restapi/Sqlqueries.java(1 hunks)sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlqueriesValidate.java(1 hunks)sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlqueriesValidateWithUrl.java(1 hunks)sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlqueriesWithUrl.java(1 hunks)sql_server_queries/src/main/java/com/testsigma/addons/restapi/Sqlselect.java(1 hunks)sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlselectWithUrl.java(1 hunks)sql_server_queries/src/main/java/com/testsigma/addons/restapi/Sqlselectvalidate.java(1 hunks)sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlselectvalidateWithUrl.java(1 hunks)sql_server_queries/src/main/java/com/testsigma/addons/restapi/Sqlupdatequeries.java(1 hunks)sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlupdatequeriesWithUrl.java(1 hunks)substring_removebylength/pom.xml(2 hunks)substring_removebylength/src/main/java/com/testsigma/addons/restapi/RemovePositions.java(1 hunks)xml_verification_/pom.xml(3 hunks)xml_verification_/src/main/java/com/testsigma/addons/restapi/CompareLocalXMLFiles.java(1 hunks)xml_verification_/src/main/java/com/testsigma/addons/restapi/CompareXMLTextsIgnoringXPaths.java(1 hunks)xml_verification_/src/main/java/com/testsigma/addons/restapi/ExtractTheContentOfXML.java(1 hunks)xml_verification_/src/main/java/com/testsigma/addons/utilities/XMLUtility.java(13 hunks)xml_verification_/src/main/java/com/testsigma/addons/web/CompareLocalXMLFiles.java(6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
mysql_queries/src/main/java/com/testsigma/addons/restapi/Mysqlutil.java (1)
mysql_queries/src/main/java/com/testsigma/addons/web/Mysqlutil.java (1)
Mysqlutil(3-5)
xml_verification_/src/main/java/com/testsigma/addons/restapi/CompareXMLTextsIgnoringXPaths.java (1)
xml_verification_/src/main/java/com/testsigma/addons/web/CompareXMLTextsIgnoringXPaths.java (1)
Data(15-71)
🔇 Additional comments (32)
rest_api_utils/src/main/resources/testsigma-sdk.properties (1)
1-1: Scan repository for other leaked secrets and verify none remainRun this lightweight scan to find similar credentials and JWT-like tokens across the repo.
#!/bin/bash set -euo pipefail echo "Searching for testsigma-sdk.api.key occurrences..." rg -n --color never -S --glob '!.git' 'testsigma-sdk\.api\.key\s*=' || true echo echo "Searching for common JWT-looking tokens (header.payload.signature)..." rg -n --color never -S --glob '!.git' '[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}' || true echo echo "Scanning for generic API key patterns..." rg -n --color never -S --glob '!.git' '(api[-_ ]?key|secret|token)\s*[:=]\s*[A-Za-z0-9_\-+/=]{16,}' || true echo echo "Searching for other properties files with suspicious values..." fd -e properties | xargs -I{} sh -c 'echo "--- {} ---"; sed -n "1,200p" "{}" | rg -n -S "(key|secret|token)\s*=" || true'rest_api_utils/pom.xml (5)
1-11: Module skeleton looks good.Group/artifact coordinates, packaging, and Java 11/UTF-8 defaults are standard. Good starting point for a new addon module.
16-16: Confirm testsigma-java-sdk version qualifier.The version string 1.2.24_cloud has an underscore qualifier. Ensure this exact version exists in your artifact repository and is intended for public consumption.
Run to verify availability on Maven Central (or your internal repo if applicable):
#!/bin/bash curl -s 'https://search.maven.org/solrsearch/select?q=g:%22com.testsigma%22+AND+a:%22testsigma-java-sdk%22&rows=50&wt=json' | jq '.response.docs[] | {v:.latestVersion}'If not on Central, confirm your repository settings in the parent POM.
42-46: ```shell
#!/bin/bashSearch for TestNG imports/usages in the rest_api_utils module
rg -n "import org.testng" rest_api_utils
rg -n "org.testng" rest_api_utilsCheck for @test annotations (could be JUnit or TestNG)
rg -n "@test" rest_api_utils/src/test/java
--- `59-63`: ```shell #!/usr/bin/env bash # Check if a jackson.version property is already defined echo "=== jackson.version property definitions ===" rg -n "<jackson.version>" -n . # List all Jackson dependencies and their configured versions echo "=== Jackson dependencies across all POMs ===" rg -n "<groupId>com.fasterxml.jackson" -C2 -n . # Check for an existing Jackson BOM import echo "=== Jackson BOM imports ===" rg -n "<artifactId>jackson-bom" -C2 -n .
37-41: ```shell
#!/usr/bin/env bashVerify presence of JUnit Jupiter Engine in the module POM
echo ">> Looking for junit-jupiter-engine in rest_api_utils/pom.xml"
rg -n 'junit-jupiter-engine' rest_api_utils/pom.xml || echo "✔ junit-jupiter-engine not found"echo
Verify Surefire plugin configuration in this POM
echo ">> Searching for Surefire plugin in rest_api_utils/pom.xml"
rg -n 'maven-surefire-plugin' rest_api_utils/pom.xml || echo "✔ No maven-surefire-plugin configuration found here"echo
Check for TestNG dependency to ensure no unintended mixing
echo ">> Checking for TestNG dependency in rest_api_utils/pom.xml"
rg -n 'testng' rest_api_utils/pom.xml || echo "✔ testng not found"</details> <details> <summary>substring_removebylength/pom.xml (2)</summary> `9-9`: **Version bump looks good.** Increment to 1.0.5 is clear and consistent with module changes. --- `20-20`: **Lombok upgrade aligned.** Upgrading to 1.18.30 matches the broader repo alignment. No issues spotted. </details> <details> <summary>sql_server_queries/pom.xml (2)</summary> `9-9`: **Version bump acknowledged.** 2.0.3 version increment noted; no issues. --- `20-20`: **Lombok 1.18.30 update is consistent.** Matches other modules; good to go. </details> <details> <summary>xml_verification_/pom.xml (1)</summary> `69-74`: **Commons IO upgrade to 2.16.1 looks good.** Recent version with fixes; no immediate conflicts expected. </details> <details> <summary>mysql_queries/pom.xml (2)</summary> `9-9`: **Version bump looks appropriate.** The version increment from 1.0.14 to 1.0.16 aligns with the MySQL driver update and addition of new functionality. --- `70-75`: **Confirm MySQL Connector/J 8.3.0 Security & Compatibility** Verified: Connector/J 8.3.0 has no known, unfixed security vulnerabilities. However, this upgrade introduces breaking changes that may impact your application: • Character set/collation mapping updates (e.g. `utf8_` → `utf8mb3_`) • Stricter validation on negative connection-property values (e.g. `maxAllowedPacket`, `resultSetSizeThreshold`) • Independent handling of `allowMultiQueries` vs. `rewriteBatchedStatements` • Clarified exception messages for negative `Statement.setMaxRows()` arguments • Updated cipher‐suite requirements and dependency versions Please review any usages of legacy charsets/collations, negative property values, and batching/multi‐query logic in your code and run integration tests against your target MySQL server versions to ensure full compatibility. </details> <details> <summary>sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlupdatequeriesWithUrl.java (2)</summary> `40-43`: **LGTM! Good connection and query execution pattern.** The implementation correctly obtains a connection using DatabaseUtil and executes the update query, capturing the affected row count. --- `56-68`: **Excellent resource management.** The finally block properly closes database resources with null checks and exception handling, preventing resource leaks. </details> <details> <summary>sql_server_queries/src/main/java/com/testsigma/addons/restapi/Sqlupdatequeries.java (1)</summary> `61-73`: **Excellent resource management.** The finally block properly handles resource cleanup with null checks and exception handling, preventing resource leaks. </details> <details> <summary>xml_verification_/src/main/java/com/testsigma/addons/restapi/ExtractTheContentOfXML.java (1)</summary> `53-56`: **LGTM! Proper runtime data handling.** The XML content is correctly logged and stored in the runtime variable with appropriate key assignment. </details> <details> <summary>sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlselectWithUrl.java (1)</summary> `92-107`: **Excellent resource management.** The finally block properly closes all database resources (ResultSet, Statement, Connection) with null checks and exception handling, preventing resource leaks. </details> <details> <summary>sql_server_queries/src/main/java/com/testsigma/addons/restapi/Sqlqueries.java (1)</summary> `76-91`: **LGTM! Proper resource management.** Excellent implementation of resource cleanup in the finally block with proper exception handling. </details> <details> <summary>sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlqueriesValidateWithUrl.java (2)</summary> `81-96`: **LGTM! Comprehensive resource management.** Excellent implementation of proper resource cleanup with detailed error handling. --- `60-72`: **LGTM! Robust validation logic.** The comparison logic properly handles both expected and actual values with detailed error messaging. </details> <details> <summary>mssqldb_queries/src/main/java/com/testsigma/addons/web/MSSqlValidateIOS.java (1)</summary> `55-69`: **LGTM! Clear validation logic with proper messaging.** The validation logic correctly counts matches and provides clear success/failure messages with expected values. </details> <details> <summary>mysql_queries/src/main/java/com/testsigma/addons/restapi/MysqlqueriesValidate.java (1)</summary> `3-3`: **Incorrect import path for MySQL DatabaseUtil** This MySQL action imports DatabaseUtil from `com.testsigma.addons.mysql.util` but the file path suggests it should be using a MySQL-specific utility, not the MSSQL one mentioned in the AI summary. ```shell #!/bin/bash # Check if MySQL-specific DatabaseUtil exists and where it's located fd -t f "DatabaseUtil.java" | xargs grep -l "mysql" 2>/dev/null # Check the actual package structure for mysql_queries module fd -t d "mysql" | grep -E "util|mysql_queries"xml_verification_/src/main/java/com/testsigma/addons/utilities/XMLUtility.java (3)
469-474: Good improvement: Enhanced observability with logger injectionThe addition of logger to the DomBuilderWithLineNumbers class improves debugging capabilities by enabling detailed logging of DOM construction events.
164-173: Smart enhancement: Parent-aware text difference reportingThe improvement to report text differences using the parent element's context and line numbers makes the error messages more actionable and easier to locate in the source XML.
191-197: Well-designed path matching logicThe path matching logic correctly handles both exact matches and prefix matches while avoiding false positives (e.g., "/root/a" won't match "/root/ab").
sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlqueriesValidate.java (2)
48-78: Critical: Resources not closed on successful executionThe database resources (ResultSet, Statement, Connection) are only closed in the finally block, which is correct. However, the current implementation has a potential resource leak if an exception occurs between resource creation and the finally block.
The resource cleanup in the finally block is properly implemented and will handle all scenarios correctly.
43-43: Security: Consider using encrypted connectionsThe connection string explicitly sets
encrypt=false, which could expose sensitive data in transit. Consider making encryption configurable or defaulting to true for production use.Would you like me to check if there are organizational security guidelines for database connections that should be followed?
sql_server_queries/src/main/java/com/testsigma/addons/restapi/Sqlselectvalidate.java (1)
79-94: Excellent resource management.The finally block properly closes all JDBC resources with appropriate null checks and exception handling. This is a good practice that should be followed in the other similar classes.
sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlqueriesWithUrl.java (1)
36-86: Add resource cleanup to prevent connection leaksThe
Connection,Statement, andResultSetare obtained but never closed in the try block, which could lead to resource leaks if exceptions occur before the finally block.The resources should be declared in the try block scope and closed in the finally block (which is already present but the declarations need to be moved up):
public Result execute() throws NoSuchElementException { Result result = Result.SUCCESS; logger.info("Initiating execution"); String url = databaseUrl.getValue().toString(); DatabaseUtil databaseUtil = new DatabaseUtil(); Connection connection = null; Statement stmt = null; ResultSet resultSet = null; try{ connection = databaseUtil.getConnection(url); stmt = connection.createStatement(); String query = testData1.getValue().toString(); resultSet = stmt.executeQuery(query);Likely an incorrect or invalid review comment.
sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlValidateQueriesonTablesWithUrl.java (1)
75-99: Good resource cleanup implementationThe finally block properly handles resource cleanup with null checks and exception handling. This prevents resource leaks.
xml_verification_/src/main/java/com/testsigma/addons/web/CompareLocalXMLFiles.java (1)
42-42: Remove unnecessary XMLUtility constructor parametersThe comment suggests XMLUtility needs driver/logger, but for a web action comparing local files, the driver parameter seems unnecessary. Verify if XMLUtility actually requires these parameters for this use case.
#!/bin/bash # Check XMLUtility constructor and its usage ast-grep --pattern 'class XMLUtility { $$$ }' # Check if XMLUtility constructor is used elsewhere rg -A 5 "new XMLUtility\("
| <dependency> | ||
| <groupId>com.microsoft.sqlserver</groupId> | ||
| <artifactId>mssql-jdbc</artifactId> | ||
| <version>10.2.0.jre11</version> | ||
| </dependency> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Verify MSSQL JDBC driver version for security and compatibility.
The MSSQL JDBC driver version 10.2.0.jre11 should be checked for security vulnerabilities and compatibility with the target Java version.
🌐 Web query:
Are there any known security vulnerabilities in Microsoft MSSQL JDBC driver version 10.2.0.jre11? What is the latest stable version available?
💡 Result:
Microsoft MSSQL JDBC driver version 10.2.0.jre11 is known to have several security vulnerabilities in its dependencies, some with published CVEs. The latest stable version of the driver as of August 2025 is 12.10.1.
Security vulnerabilities in 10.2.0.jre11:
- The Maven repository lists multiple vulnerabilities related to this version and/or its dependencies, specifically:
- Some vulnerabilities affect optional components such as Azure Identity and BouncyCastle cryptography libraries, but this may still pose a risk depending on your usage and configuration[2].
Latest stable version:
- The most recent general availability (GA) release is 12.10.1, released on June 18, 2025, which supports Java 8, 11, 17, 21, and 23. It is strongly recommended to use the latest driver to ensure access to security updates and fixes[1][3][5].
Version summary table:
| Driver Version | Release Date | Java Support | Notes |
|---|---|---|---|
| 10.2.0.jre11 | Feb 1, 2022 | Java 11, 17 | Contains CVEs[2][6] |
| 12.10.1 | Jun 18, 2025 | Java 8, 11, 17, 21, 23 | Latest stable version[1][3] |
Recommendation:
- For secure deployments, upgrade to at least version 12.10.1 or later to benefit from ongoing security and compatibility updates. Running older versions, especially with published CVEs, increases risk—even if component vulnerabilities are in optional dependencies, they may still affect your environment depending on configuration[2][1][3].
If you require details about specific CVEs or compatibility for your application stack, it is best to refer to the official Microsoft JDBC release notes or your security team for a deeper review.
Citations:
- 1: https://learn.microsoft.com/en-us/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-ver17
- 2: https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc/10.2.0.jre11
- 3: https://learn.microsoft.com/vi-vn/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-ver16
- 4: https://techcommunity.microsoft.com/blog/sqlserver/jdbc-driver-10-2-for-sql-server-released/3100754
- 5: https://learn.microsoft.com/en-us/sql/connect/jdbc/release-notes-for-the-jdbc-driver?view=sql-server-ver17
- 6: https://learn.microsoft.com/en-us/sql/connect/jdbc/using-the-jdbc-driver?view=sql-server-ver17
- 7: https://techcommunity.microsoft.com/blog/sqlserver/early-technical-preview-of-jdbc-driver-13-1-0-for-sql-server-released/4428995
- 8: https://cve.mitre.org/cgi-bin/cvekey.cgi
- 9: https://learn.microsoft.com/en-us/sql/connect/jdbc/system-requirements-for-the-jdbc-driver?view=sql-server-ver17
- 10: https://help.uplandsoftware.com/objectiflune/en/archive/OLConnect-Desktop-Installation-Guide-2024-1.pdf
Action Required: Upgrade MSSQL JDBC driver to 12.10.1 for security and compatibility
The currently pinned version (10.2.0.jre11) carries several published CVEs and is out-of-date. Please update to the latest GA release (12.10.1) to receive critical security fixes and broadened Java support.
• Location to update:
- File: mssqldb_queries/pom.xml
- Lines: 58–62
• Key findings:
- Version 10.2.0.jre11 is affected by CVE-2024-35255, CVE-2024-30171, CVE-2024-29857, CVE-2023-33201, CVE-2022-45868.
- Latest stable release (12.10.1, June 2025) supports Java 8, 11, 17, 21, 23 and contains all upstream fixes.
• Recommended change:
--- a/mssqldb_queries/pom.xml
+++ b/mssqldb_queries/pom.xml
@@ lines 58-62
- <dependency>
- <groupId>com.microsoft.sqlserver</groupId>
- <artifactId>mssql-jdbc</artifactId>
- <version>10.2.0.jre11</version>
- </dependency>
+ <dependency>
+ <groupId>com.microsoft.sqlserver</groupId>
+ <artifactId>mssql-jdbc</artifactId>
+ <version>12.10.1</version>
+ </dependency>📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| <dependency> | |
| <groupId>com.microsoft.sqlserver</groupId> | |
| <artifactId>mssql-jdbc</artifactId> | |
| <version>10.2.0.jre11</version> | |
| </dependency> | |
| <dependency> | |
| <groupId>com.microsoft.sqlserver</groupId> | |
| <artifactId>mssql-jdbc</artifactId> | |
| <version>12.10.1</version> | |
| </dependency> |
🤖 Prompt for AI Agents
In mssqldb_queries/pom.xml around lines 58 to 62, the Maven dependency for the
Microsoft SQL Server JDBC driver is pinned to 10.2.0.jre11 which is vulnerable
and out of date; update the <version> element for the
com.microsoft.sqlserver:mssql-jdbc dependency to 12.10.1, save the pom, run mvn
-U verify (or your project's build) to refresh dependencies and ensure the
project compiles and tests pass, and commit the updated pom.xml.
| <configuration> | ||
| <minimizeJar>true</minimizeJar> | ||
| <filters> | ||
| <filter> | ||
| <artifact>*:*</artifact> | ||
| <excludes> | ||
| <exclude>META-INF/*.SF</exclude> | ||
| <exclude>META-INF/*.DSA</exclude> | ||
| <exclude>META-INF/*.RSA</exclude> | ||
| </excludes> | ||
| </filter> | ||
| </filters> | ||
| </configuration> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Review minimizeJar configuration for potential issues.
The minimizeJar configuration may exclude necessary dependencies or resources that are loaded dynamically by the MSSQL JDBC driver or other dependencies. This could cause runtime failures when classes are loaded via reflection.
Consider adding explicit inclusions for classes that might be loaded dynamically:
<configuration>
- <minimizeJar>true</minimizeJar>
+ <minimizeJar>false</minimizeJar>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>Or if you must use minimizeJar, add explicit inclusions:
<configuration>
<minimizeJar>true</minimizeJar>
+ <artifactSet>
+ <includes>
+ <include>com.microsoft.sqlserver:mssql-jdbc</include>
+ </includes>
+ </artifactSet>
<filters>📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| <configuration> | |
| <minimizeJar>true</minimizeJar> | |
| <filters> | |
| <filter> | |
| <artifact>*:*</artifact> | |
| <excludes> | |
| <exclude>META-INF/*.SF</exclude> | |
| <exclude>META-INF/*.DSA</exclude> | |
| <exclude>META-INF/*.RSA</exclude> | |
| </excludes> | |
| </filter> | |
| </filters> | |
| </configuration> | |
| <configuration> | |
| <minimizeJar>false</minimizeJar> | |
| <filters> | |
| <filter> | |
| <artifact>*:*</artifact> | |
| <excludes> | |
| <exclude>META-INF/*.SF</exclude> | |
| <exclude>META-INF/*.DSA</exclude> | |
| <exclude>META-INF/*.RSA</exclude> | |
| </excludes> | |
| </filter> | |
| </filters> | |
| </configuration> |
| <configuration> | |
| <minimizeJar>true</minimizeJar> | |
| <filters> | |
| <filter> | |
| <artifact>*:*</artifact> | |
| <excludes> | |
| <exclude>META-INF/*.SF</exclude> | |
| <exclude>META-INF/*.DSA</exclude> | |
| <exclude>META-INF/*.RSA</exclude> | |
| </excludes> | |
| </filter> | |
| </filters> | |
| </configuration> | |
| <configuration> | |
| <minimizeJar>true</minimizeJar> | |
| <artifactSet> | |
| <includes> | |
| <include>com.microsoft.sqlserver:mssql-jdbc</include> | |
| </includes> | |
| </artifactSet> | |
| <filters> | |
| <filter> | |
| <artifact>*:*</artifact> | |
| <excludes> | |
| <exclude>META-INF/*.SF</exclude> | |
| <exclude>META-INF/*.DSA</exclude> | |
| <exclude>META-INF/*.RSA</exclude> | |
| </excludes> | |
| </filter> | |
| </filters> | |
| </configuration> |
🤖 Prompt for AI Agents
In mssqldb_queries/pom.xml around lines 78-90, the current minimizeJar(true)
configuration can strip classes/resources loaded reflectively (e.g., MSSQL JDBC
driver, service provider files, META-INF/services), causing runtime failures;
either disable minimization by setting minimizeJar to false or, if you must keep
it, add explicit inclusions for the JDBC driver packages and any
classes/resources loaded via reflection (e.g., com.microsoft.sqlserver.* and
related SPI/service files, META-INF/services/* and any native/resource paths) so
those entries are preserved, then rebuild and smoke-test DB connectivity.
| public Connection getConnection(String dbURL) throws Exception { | ||
|
|
||
| Class.forName(dbClass).getDeclaredConstructor().newInstance(); | ||
| Connection con = DriverManager.getConnection(dbURL); | ||
| return con; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical security and resource management issues.
This method has several critical problems:
- SQL Injection Risk: Accepts raw database URLs without validation
- Resource Leak: Connections are never closed, leading to connection pool exhaustion
- Driver Loading: Unnecessary driver instantiation on every call
- No Authentication: No secure credential handling
Refactor the utility to address these issues:
public class DatabaseUtil {
- private String dbClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
+ private static final String DRIVER_CLASS = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
+
+ static {
+ try {
+ Class.forName(DRIVER_CLASS);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException("Failed to load MSSQL driver", e);
+ }
+ }
+
public Connection getConnection(String dbURL) throws Exception {
- Class.forName(dbClass).getDeclaredConstructor().newInstance();
- Connection con = DriverManager.getConnection(dbURL);
- return con;
+ if (dbURL == null || dbURL.trim().isEmpty()) {
+ throw new IllegalArgumentException("Database URL cannot be null or empty");
+ }
+ return DriverManager.getConnection(dbURL);
}
+
+ // Consider adding a method that accepts credentials separately
+ public Connection getConnection(String dbURL, String username, String password) throws Exception {
+ if (dbURL == null || dbURL.trim().isEmpty()) {
+ throw new IllegalArgumentException("Database URL cannot be null or empty");
+ }
+ return DriverManager.getConnection(dbURL, username, password);
+ }
}Important: Ensure that calling code properly closes connections using try-with-resources or finally blocks.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public Connection getConnection(String dbURL) throws Exception { | |
| Class.forName(dbClass).getDeclaredConstructor().newInstance(); | |
| Connection con = DriverManager.getConnection(dbURL); | |
| return con; | |
| } | |
| public class DatabaseUtil { | |
| private static final String DRIVER_CLASS = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; | |
| static { | |
| try { | |
| Class.forName(DRIVER_CLASS); | |
| } catch (ClassNotFoundException e) { | |
| throw new RuntimeException("Failed to load MSSQL driver", e); | |
| } | |
| } | |
| public Connection getConnection(String dbURL) throws Exception { | |
| if (dbURL == null || dbURL.trim().isEmpty()) { | |
| throw new IllegalArgumentException("Database URL cannot be null or empty"); | |
| } | |
| return DriverManager.getConnection(dbURL); | |
| } | |
| // Consider adding a method that accepts credentials separately | |
| public Connection getConnection(String dbURL, String username, String password) throws Exception { | |
| if (dbURL == null || dbURL.trim().isEmpty()) { | |
| throw new IllegalArgumentException("Database URL cannot be null or empty"); | |
| } | |
| return DriverManager.getConnection(dbURL, username, password); | |
| } | |
| } |
| try{ | ||
| Connection connection = databaseUtil.getConnection(testData2.getValue().toString()); | ||
| Statement stmt = connection.createStatement(); | ||
| String query = testData1.getValue().toString(); | ||
| ResultSet resultSet = stmt.executeQuery(query); | ||
| resultSet.next(); | ||
| String resultData = resultSet.getObject(1).toString(); | ||
| runTimeData = new com.testsigma.sdk.RunTimeData(); | ||
| runTimeData.setValue(resultData); | ||
| runTimeData.setKey(testData3.getValue().toString()); | ||
| setSuccessMessage("Successfully Executed Select Query and Resultset is : " +resultData); | ||
| logger.info("Successfully Executed Select Query and Resultset is : " +resultData); | ||
| } | ||
| catch (Exception e){ | ||
| String errorMessage = ExceptionUtils.getStackTrace(e); | ||
| result = Result.FAILED; | ||
| setErrorMessage(errorMessage); | ||
| logger.warn(errorMessage); | ||
| } | ||
| return result; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add resource cleanup in finally block.
The code opens database connections but doesn't ensure they're properly closed, which can lead to resource leaks.
Add proper resource management:
DatabaseUtil databaseUtil = new DatabaseUtil();
+ Connection connection = null;
+ Statement stmt = null;
+ ResultSet resultSet = null;
try{
- Connection connection = databaseUtil.getConnection(testData2.getValue().toString());
- Statement stmt = connection.createStatement();
+ connection = databaseUtil.getConnection(testData2.getValue().toString());
+ stmt = connection.createStatement();
String query = testData1.getValue().toString();
- ResultSet resultSet = stmt.executeQuery(query);
+ resultSet = stmt.executeQuery(query);
// ... existing logic
}
catch (Exception e){
// ... existing error handling
}
+ finally {
+ try {
+ if (resultSet != null) resultSet.close();
+ if (stmt != null) stmt.close();
+ if (connection != null) connection.close();
+ } catch (Exception e) {
+ logger.warn("Error closing resources: " + e.getMessage());
+ }
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try{ | |
| Connection connection = databaseUtil.getConnection(testData2.getValue().toString()); | |
| Statement stmt = connection.createStatement(); | |
| String query = testData1.getValue().toString(); | |
| ResultSet resultSet = stmt.executeQuery(query); | |
| resultSet.next(); | |
| String resultData = resultSet.getObject(1).toString(); | |
| runTimeData = new com.testsigma.sdk.RunTimeData(); | |
| runTimeData.setValue(resultData); | |
| runTimeData.setKey(testData3.getValue().toString()); | |
| setSuccessMessage("Successfully Executed Select Query and Resultset is : " +resultData); | |
| logger.info("Successfully Executed Select Query and Resultset is : " +resultData); | |
| } | |
| catch (Exception e){ | |
| String errorMessage = ExceptionUtils.getStackTrace(e); | |
| result = Result.FAILED; | |
| setErrorMessage(errorMessage); | |
| logger.warn(errorMessage); | |
| } | |
| return result; | |
| DatabaseUtil databaseUtil = new DatabaseUtil(); | |
| Connection connection = null; | |
| Statement stmt = null; | |
| ResultSet resultSet = null; | |
| try { | |
| connection = databaseUtil.getConnection(testData2.getValue().toString()); | |
| stmt = connection.createStatement(); | |
| String query = testData1.getValue().toString(); | |
| resultSet = stmt.executeQuery(query); | |
| resultSet.next(); | |
| String resultData = resultSet.getObject(1).toString(); | |
| runTimeData = new com.testsigma.sdk.RunTimeData(); | |
| runTimeData.setValue(resultData); | |
| runTimeData.setKey(testData3.getValue().toString()); | |
| setSuccessMessage("Successfully Executed Select Query and Resultset is : " + resultData); | |
| logger.info("Successfully Executed Select Query and Resultset is : " + resultData); | |
| } catch (Exception e) { | |
| String errorMessage = ExceptionUtils.getStackTrace(e); | |
| result = Result.FAILED; | |
| setErrorMessage(errorMessage); | |
| logger.warn(errorMessage); | |
| } finally { | |
| try { | |
| if (resultSet != null) resultSet.close(); | |
| if (stmt != null) stmt.close(); | |
| if (connection != null) connection.close(); | |
| } catch (Exception e) { | |
| logger.warn("Error closing resources: " + e.getMessage()); | |
| } | |
| } | |
| return result; |
🤖 Prompt for AI Agents
In
mssqldb_queries/src/main/java/com/testsigma/addons/restapi/MSSqlStoreselect.java
around lines 39-58, the try block opens a Connection, Statement and ResultSet
but never closes them; add proper resource cleanup by moving resource creation
into a try-with-resources (preferred) or add a finally block that closes
resultSet, stmt and connection in reverse order with null checks and each close
wrapped in its own try/catch to swallow/log any SQLException; ensure the
resources are closed regardless of success or failure and remove any premature
returns that would bypass cleanup.
| resultSet.next(); | ||
| String resultData = resultSet.getObject(1).toString(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add validation for empty result set.
The code calls resultSet.next() and resultSet.getObject(1) without checking if the result set has any rows, which will cause exceptions for empty results.
ResultSet resultSet = stmt.executeQuery(query);
- resultSet.next();
- String resultData = resultSet.getObject(1).toString();
+ if (resultSet.next()) {
+ Object firstCell = resultSet.getObject(1);
+ String resultData = firstCell != null ? firstCell.toString() : "NULL";
+ } else {
+ throw new SQLException("Query returned no results");
+ }Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In
mssqldb_queries/src/main/java/com/testsigma/addons/restapi/MSSqlStoreselect.java
around lines 44-45, the code unconditionally calls resultSet.next() and then
resultSet.getObject(1) which will throw if the result set is empty; change the
logic to check the boolean returned by resultSet.next() before calling
getObject(1) and handle the empty case (for example return null or an empty
string, or throw a clear exception) so you never call getObject on no row, and
ensure any resources/streams remain correctly handled in that branch.
| @@ -0,0 +1,61 @@ | |||
| package com.testsigma.addons.restapi; | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix incorrect package declaration.
The class is located in substring_removebylength module but uses the restapi package name, which is inconsistent with the module structure.
-package com.testsigma.addons.restapi;
+package com.testsigma.addons.substring;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| package com.testsigma.addons.restapi; | |
| -package com.testsigma.addons.restapi; | |
| +package com.testsigma.addons.substring; |
🤖 Prompt for AI Agents
In
substring_removebylength/src/main/java/com/testsigma/addons/restapi/RemovePositions.java
around line 1, the file declares the wrong package (restapi) for the
substring_removebylength module; change the package declaration to the correct
package that matches the module and directory structure (for example
com.testsigma.addons.substring_removebylength or whatever package path matches
src/main/java), ensure the package statement matches the filesystem path, then
update any imports/usages and build/config files if they reference the old
package name so compilation and runtime class resolution remain correct.
| String[] Split = testData1.getValue().toString().split(","); | ||
| String first = Split[0]; | ||
| String last = Split[1]; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve variable naming and add input validation.
Variable names Split, first, and last don't follow Java naming conventions. Also, there's no validation for the comma-separated input format.
- String[] Split = testData1.getValue().toString().split(",");
- String first = Split[0];
- String last = Split[1];
+ String[] positions = testData1.getValue().toString().split(",");
+ if (positions.length != 2) {
+ throw new IllegalArgumentException("Expected format: 'first,last' but got: " + testData1.getValue().toString());
+ }
+ String firstStr = positions[0].trim();
+ String lastStr = positions[1].trim();📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| String[] Split = testData1.getValue().toString().split(","); | |
| String first = Split[0]; | |
| String last = Split[1]; | |
| String[] positions = testData1.getValue().toString().split(","); | |
| if (positions.length != 2) { | |
| throw new IllegalArgumentException("Expected format: 'first,last' but got: " + testData1.getValue().toString()); | |
| } | |
| String firstStr = positions[0].trim(); | |
| String lastStr = positions[1].trim(); |
| if (inputString.length() >= 2) { | ||
| String resultstring = inputString.substring(Integer.parseInt(first), inputString.length() - Integer.parseInt(last)); | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add bounds checking for substring operation.
The current logic doesn't validate that the parsed integers are within valid bounds, which could lead to StringIndexOutOfBoundsException.
- if (inputString.length() >= 2) {
- String resultstring = inputString.substring(Integer.parseInt(first), inputString.length() - Integer.parseInt(last));
+ int firstPos = Integer.parseInt(firstStr);
+ int lastPos = Integer.parseInt(lastStr);
+
+ if (firstPos < 0 || lastPos < 0) {
+ throw new IllegalArgumentException("Position values must be non-negative");
+ }
+
+ int endIndex = inputString.length() - lastPos;
+ if (firstPos >= inputString.length() || endIndex <= firstPos) {
+ throw new IllegalArgumentException("Invalid position values for string length " + inputString.length());
+ }
+
+ String resultstring = inputString.substring(firstPos, endIndex);Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In
substring_removebylength/src/main/java/com/testsigma/addons/restapi/RemovePositions.java
around lines 39 to 41, the code parses 'first' and 'last' and calls substring
without validating bounds; add validation and safe parsing: parse first and last
inside a try/catch for NumberFormatException (fall back to 0 if invalid), ensure
both parsed values are >= 0, compute startIndex = Math.min(parsedFirst,
inputString.length()), compute endIndex = Math.max(startIndex,
inputString.length() - parsedLast) and clamp endIndex to inputString.length();
only call inputString.substring(startIndex, endIndex) when startIndex <=
endIndex, otherwise return "" or the original input per existing behavior; this
prevents StringIndexOutOfBoundsException.
| } else { | ||
| result = com.testsigma.sdk.Result.FAILED; | ||
| logger.warn("Input string must have at least two characters."); | ||
| setErrorMessage("Input string must have at least two characters."); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Remove obsolete length check.
With proper bounds validation added above, this simplistic length check is no longer needed and the error message is inaccurate.
- } else {
- result = com.testsigma.sdk.Result.FAILED;
- logger.warn("Input string must have at least two characters.");
- setErrorMessage("Input string must have at least two characters.");
- }Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In
substring_removebylength/src/main/java/com/testsigma/addons/restapi/RemovePositions.java
around lines 48 to 52, remove the obsolete else block that sets result to
FAILED, logs "Input string must have at least two characters.", and calls
setErrorMessage with the same text; this length check is redundant given
upstream bounds validation, so delete that entire else branch and its statements
and let earlier validation handle errors (do not introduce a new error message
or result assignment here).
| try { | ||
| HttpClient client = HttpClient.newHttpClient(); | ||
| HttpRequest request = HttpRequest.newBuilder() | ||
| .uri(new URI(filepath.getValue().toString())) | ||
| .build(); | ||
|
|
||
| HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); | ||
|
|
||
| String xmlContent = new String(response.body().readAllBytes(), StandardCharsets.UTF_8); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Resource leak with InputStream.
The InputStream from the HTTP response is not properly closed, leading to potential resource leaks.
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(filepath.getValue().toString()))
.build();
- HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
-
- String xmlContent = new String(response.body().readAllBytes(), StandardCharsets.UTF_8);
+ HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
+ String xmlContent;
+ try (InputStream inputStream = response.body()) {
+ xmlContent = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try { | |
| HttpClient client = HttpClient.newHttpClient(); | |
| HttpRequest request = HttpRequest.newBuilder() | |
| .uri(new URI(filepath.getValue().toString())) | |
| .build(); | |
| HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); | |
| String xmlContent = new String(response.body().readAllBytes(), StandardCharsets.UTF_8); | |
| try { | |
| HttpClient client = HttpClient.newHttpClient(); | |
| HttpRequest request = HttpRequest.newBuilder() | |
| .uri(new URI(filepath.getValue().toString())) | |
| .build(); | |
| HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); | |
| String xmlContent; | |
| try (InputStream inputStream = response.body()) { | |
| xmlContent = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); | |
| } |
🤖 Prompt for AI Agents
In
xml_verification_/src/main/java/com/testsigma/addons/restapi/ExtractTheContentOfXML.java
around lines 42 to 50, the InputStream returned by response.body() is never
closed which can leak resources; change the code to obtain the InputStream into
a variable and wrap the read in a try-with-resources block (or explicitly close
the stream in a finally) so the stream is closed after reading, then build the
String from the stream bytes inside that block and propagate or handle
exceptions as appropriate.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review continued from previous batch...
| private com.testsigma.sdk.TestData testData1; | ||
| @TestData(reference = "DB_Connection_URL") | ||
| private com.testsigma.sdk.TestData testData2; | ||
| StringBuffer sb = new StringBuffer(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Move StringBuffer inside the execute method
The StringBuffer field is only used within the execute() method and should be declared locally to avoid potential issues with concurrent executions in multi-threaded environments.
-StringBuffer sb = new StringBuffer();
@Override
public Result execute() throws NoSuchElementException {
+ StringBuilder sb = new StringBuilder();
Result result = Result.SUCCESS;Also prefer StringBuilder over StringBuffer as it's more efficient when thread-safety is not required.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| StringBuffer sb = new StringBuffer(); | |
| -StringBuffer sb = new StringBuffer(); | |
| @Override | |
| public Result execute() throws NoSuchElementException { | |
| + StringBuilder sb = new StringBuilder(); | |
| Result result = Result.SUCCESS; | |
| // ... rest of method unchanged | |
| } |
🤖 Prompt for AI Agents
In mssqldb_queries/src/main/java/com/testsigma/addons/restapi/MSSqlselect.java
around line 29, the StringBuffer is declared as a field but is only used inside
execute(); move the declaration into the execute() method as a local variable,
replace StringBuffer with StringBuilder (since thread-safety isn't required) and
remove the now-unused field to prevent shared-state issues in concurrent
executions.
| try{ | ||
| Connection connection = databaseUtil.getConnection(testData2.getValue().toString()); | ||
| Statement stmt = connection.createStatement(); | ||
| String query = testData1.getValue().toString(); | ||
| ResultSet resultSet = stmt.executeQuery(query); | ||
| ResultSetMetaData rsmd = resultSet.getMetaData(); | ||
| int columnNo = resultSet.getMetaData().getColumnCount(); | ||
| sb.append("Successfully Executed Select Query and Resultset is : " + "<br>"); | ||
| for (int i = 1; i <= columnNo; i++) { | ||
| sb.append(rsmd.getColumnName(i)); | ||
| sb.append(", "); | ||
| } | ||
| sb.append("<br>"); | ||
| while (resultSet.next()) { | ||
| for (int j = 1; j <= columnNo; j++) { | ||
| if (j > 1) sb.append(", "); | ||
| String columnValue = resultSet.getString(j); | ||
| if (resultSet.wasNull()) { | ||
| sb.append(""); | ||
| } | ||
| sb.append(columnValue); | ||
| } | ||
| sb.append("<br>"); | ||
| } | ||
| setSuccessMessage(sb.toString()); | ||
| logger.info(sb.toString()); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Database resources are not properly closed
Connection, Statement, and ResultSet resources are not closed after use, which will lead to resource leaks and potential database connection pool exhaustion.
Add proper resource management using try-with-resources:
-try{
- Connection connection = databaseUtil.getConnection(testData2.getValue().toString());
- Statement stmt = connection.createStatement();
- String query = testData1.getValue().toString();
- ResultSet resultSet = stmt.executeQuery(query);
+try (Connection connection = databaseUtil.getConnection(testData2.getValue().toString());
+ Statement stmt = connection.createStatement();
+ ResultSet resultSet = stmt.executeQuery(testData1.getValue().toString())) {
+
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnNo = resultSet.getMetaData().getColumnCount();📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try{ | |
| Connection connection = databaseUtil.getConnection(testData2.getValue().toString()); | |
| Statement stmt = connection.createStatement(); | |
| String query = testData1.getValue().toString(); | |
| ResultSet resultSet = stmt.executeQuery(query); | |
| ResultSetMetaData rsmd = resultSet.getMetaData(); | |
| int columnNo = resultSet.getMetaData().getColumnCount(); | |
| sb.append("Successfully Executed Select Query and Resultset is : " + "<br>"); | |
| for (int i = 1; i <= columnNo; i++) { | |
| sb.append(rsmd.getColumnName(i)); | |
| sb.append(", "); | |
| } | |
| sb.append("<br>"); | |
| while (resultSet.next()) { | |
| for (int j = 1; j <= columnNo; j++) { | |
| if (j > 1) sb.append(", "); | |
| String columnValue = resultSet.getString(j); | |
| if (resultSet.wasNull()) { | |
| sb.append(""); | |
| } | |
| sb.append(columnValue); | |
| } | |
| sb.append("<br>"); | |
| } | |
| setSuccessMessage(sb.toString()); | |
| logger.info(sb.toString()); | |
| } | |
| try (Connection connection = databaseUtil.getConnection(testData2.getValue().toString()); | |
| Statement stmt = connection.createStatement(); | |
| ResultSet resultSet = stmt.executeQuery(testData1.getValue().toString())) { | |
| ResultSetMetaData rsmd = resultSet.getMetaData(); | |
| int columnNo = rsmd.getColumnCount(); | |
| sb.append("Successfully Executed Select Query and Resultset is : " + "<br>"); | |
| for (int i = 1; i <= columnNo; i++) { | |
| sb.append(rsmd.getColumnName(i)); | |
| sb.append(", "); | |
| } | |
| sb.append("<br>"); | |
| while (resultSet.next()) { | |
| for (int j = 1; j <= columnNo; j++) { | |
| if (j > 1) sb.append(", "); | |
| String columnValue = resultSet.getString(j); | |
| if (resultSet.wasNull()) { | |
| sb.append(""); | |
| } | |
| sb.append(columnValue); | |
| } | |
| sb.append("<br>"); | |
| } | |
| setSuccessMessage(sb.toString()); | |
| logger.info(sb.toString()); | |
| } |
🤖 Prompt for AI Agents
In mssqldb_queries/src/main/java/com/testsigma/addons/restapi/MSSqlselect.java
around lines 36 to 62, the Connection, Statement, and ResultSet are never closed
causing resource leaks; refactor the try block to use try-with-resources that
declares the Connection, Statement and ResultSet so they are automatically
closed (or at minimum close them in finally), move ResultSetMetaData/column
count logic inside that scope, and ensure any exceptions are caught and handled
(setFailureMessage/log) while preserving the existing success messaging.
| try{ | ||
| Connection connection = databaseUtil.getConnection(testData2.getValue().toString()); | ||
| Statement stmt = connection.createStatement(); | ||
| String query = testData1.getValue().toString(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add SQL injection protection
The query is directly executed from user input without any validation or parameterization, creating a potential SQL injection vulnerability.
Consider adding query validation or using PreparedStatement for parameterized queries where applicable. At minimum, document that this action should only be used with trusted input sources.
| private com.testsigma.sdk.TestData testData1; | ||
| @TestData(reference = "DB_Connection_URL") | ||
| private com.testsigma.sdk.TestData testData2; | ||
| StringBuffer sb = new StringBuffer(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Move StringBuffer inside the execute method
The StringBuffer field should be a local variable to avoid potential issues with concurrent executions.
-StringBuffer sb = new StringBuffer();
@Override
public com.testsigma.sdk.Result execute() throws NoSuchElementException {
+ StringBuilder sb = new StringBuilder();
Result result = Result.SUCCESS;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| StringBuffer sb = new StringBuffer(); | |
| @Override | |
| public com.testsigma.sdk.Result execute() throws NoSuchElementException { | |
| StringBuilder sb = new StringBuilder(); | |
| Result result = Result.SUCCESS; | |
| // …rest of method… | |
| } |
🤖 Prompt for AI Agents
In mssqldb_queries/src/main/java/com/testsigma/addons/web/MsSqlSelectAndroid
around line 29, the StringBuffer is declared as a class-level field which can
cause shared-state issues during concurrent executions; make it a local variable
by removing the field declaration and creating a new StringBuffer (or
StringBuilder) instance inside the execute method where it’s used, update all
references to use the local variable, and ensure no other methods rely on the
field so the class is stateless for concurrent runs.
| try{ | ||
| Connection connection = databaseUtil.getConnection(testData2.getValue().toString()); | ||
| Statement stmt = connection.createStatement(); | ||
| String query = testData1.getValue().toString(); | ||
| ResultSet resultSet = stmt.executeQuery(query); | ||
| ResultSetMetaData rsmd = resultSet.getMetaData(); | ||
| int columnNo = resultSet.getMetaData().getColumnCount(); | ||
| sb.append("Successfully Executed Select Query and Resultset is : " + "<br>"); | ||
| for (int i = 1; i <= columnNo; i++) { | ||
| sb.append(rsmd.getColumnName(i)); | ||
| sb.append(", "); | ||
| } | ||
| sb.append("<br>"); | ||
| while (resultSet.next()) { | ||
| for (int j = 1; j <= columnNo; j++) { | ||
| if (j > 1) sb.append(", "); | ||
| String columnValue = resultSet.getString(j); | ||
| if (resultSet.wasNull()) { | ||
| sb.append(""); | ||
| } | ||
| sb.append(columnValue); | ||
| } | ||
| sb.append("<br>"); | ||
| } | ||
| setSuccessMessage(sb.toString()); | ||
| logger.info(sb.toString()); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Database resources are not properly closed
Connection, Statement, and ResultSet are not closed, leading to resource leaks.
Use try-with-resources to ensure proper resource management:
-try{
- Connection connection = databaseUtil.getConnection(testData2.getValue().toString());
- Statement stmt = connection.createStatement();
- String query = testData1.getValue().toString();
- ResultSet resultSet = stmt.executeQuery(query);
+try (Connection connection = databaseUtil.getConnection(testData2.getValue().toString());
+ Statement stmt = connection.createStatement();
+ ResultSet resultSet = stmt.executeQuery(testData1.getValue().toString())) {🤖 Prompt for AI Agents
In
mssqldb_queries/src/main/java/com/testsigma/addons/web/MsSqlSelectAndroid.java
around lines 36 to 62, the Connection, Statement and ResultSet are opened but
never closed causing resource leaks; refactor this block to use
try-with-resources: obtain the Connection, create the Statement and execute the
query inside a single or nested try-with-resources so ResultSet, Statement and
Connection are auto-closed, move result processing inside that try, add a catch
for SQLException (log the error and call setFailureMessage or setSuccessMessage
with an error string as appropriate), and remove any manual closing; ensure
setSuccessMessage is only called after successful processing.
| if (resultStringBuilder.length() > 0) { | ||
| resultStringBuilder.setLength(resultStringBuilder.length() - 2); | ||
| String concatenatedResult = resultStringBuilder.toString(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Incorrect string manipulation that removes wrong characters
The code removes the last 2 characters which would be "\n" from the last row, not the trailing comma. This results in incomplete data.
- if (resultStringBuilder.length() > 0) {
- resultStringBuilder.setLength(resultStringBuilder.length() - 2);
+ if (resultStringBuilder.length() > 0 && resultStringBuilder.charAt(resultStringBuilder.length() - 1) == '\n') {
+ resultStringBuilder.setLength(resultStringBuilder.length() - 1);Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In sql_server_queries/src/main/java/com/testsigma/addons/restapi/Sqlselect.java
around lines 78-80, the code unconditionally trims the last two characters from
resultStringBuilder (assuming "\n") which actually removes data; change the
logic to remove only the trailing delimiter (e.g. ", " or a single comma) rather
than arbitrary two chars: after building rows, check if resultStringBuilder
endsWith(", ") (or endsWith(",") if you append just a comma) and then
setLength(resultStringBuilder.length() - 2) (or -1 for a single comma);
alternatively use a join approach or delete the last delimiter via
resultStringBuilder.delete(resultStringBuilder.length() - delimiter.length(),
resultStringBuilder.length()) but only when the builder length is greater than
the delimiter length.
| catch (Exception e){ | ||
| String errorMessage = ExceptionUtils.getStackTrace(e); | ||
| result = Result.FAILED; | ||
| setErrorMessage(errorMessage); | ||
| logger.warn(errorMessage); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Include original exception as the cause for better debugging
When catching and re-throwing exceptions, preserve the original exception for better stack trace information.
catch (Exception e){
String errorMessage = ExceptionUtils.getStackTrace(e);
result = Result.FAILED;
setErrorMessage(errorMessage);
- logger.warn(errorMessage);
+ logger.warn("Error executing SQL query", e);
}🤖 Prompt for AI Agents
In sql_server_queries/src/main/java/com/testsigma/addons/restapi/Sqlselect.java
around lines 88 to 93, the catch block currently logs only the stacktrace string
and loses the original exception as a cause; replace logger.warn(errorMessage)
with logger.warn(errorMessage, e) to include the original throwable in logs, and
if this code rethrows or wraps the exception later, wrap it preserving the cause
(e.g., throw new RuntimeException(errorMessage, e) or pass e as the cause to
your domain exception) so the original exception is retained for debugging.
| resultSet.next(); | ||
| String resultData = resultSet.getObject(1).toString(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Handle empty result set
The code calls resultSet.next() without checking the return value and then attempts to read from the result set. This will throw an exception if the query returns no rows.
-resultSet.next();
-String resultData = resultSet.getObject(1).toString();
+if (!resultSet.next()) {
+ result = Result.FAILED;
+ sb.append("The SELECT query returned no results.<br>");
+ setErrorMessage(sb.toString());
+ logger.warn(sb.toString());
+ return result;
+}
+Object cellValue = resultSet.getObject(1);
+if (cellValue == null) {
+ result = Result.FAILED;
+ sb.append("The first cell value is NULL.<br>");
+ setErrorMessage(sb.toString());
+ logger.warn(sb.toString());
+ return result;
+}
+String resultData = cellValue.toString();📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| resultSet.next(); | |
| String resultData = resultSet.getObject(1).toString(); | |
| if (!resultSet.next()) { | |
| result = Result.FAILED; | |
| sb.append("The SELECT query returned no results.<br>"); | |
| setErrorMessage(sb.toString()); | |
| logger.warn(sb.toString()); | |
| return result; | |
| } | |
| Object cellValue = resultSet.getObject(1); | |
| if (cellValue == null) { | |
| result = Result.FAILED; | |
| sb.append("The first cell value is NULL.<br>"); | |
| setErrorMessage(sb.toString()); | |
| logger.warn(sb.toString()); | |
| return result; | |
| } | |
| String resultData = cellValue.toString(); |
🤖 Prompt for AI Agents
In
sql_server_queries/src/main/java/com/testsigma/addons/restapi/SqlselectvalidateWithUrl.java
around lines 48-49, the code calls resultSet.next() unconditionally and then
dereferences resultSet.getObject(1), which will throw if the result set is
empty; change the logic to check the boolean returned by resultSet.next() before
accessing columns, and handle the empty case explicitly (e.g., return a clear
error/validation failure or set resultData to null/empty and log), ensuring any
resources are still closed or exceptions propagated appropriately.
| public Document parseXML(String xmlContent) throws Exception { | ||
| DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); | ||
| DocumentBuilder builder = factory.newDocumentBuilder(); | ||
| return builder.parse(new ByteArrayInputStream(xmlContent.getBytes())); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add XML parsing security configuration
The DocumentBuilder should be configured to prevent XXE (XML External Entity) attacks.
public Document parseXML(String xmlContent) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
+ factory.setXIncludeAware(false);
+ factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new ByteArrayInputStream(xmlContent.getBytes()));
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public Document parseXML(String xmlContent) throws Exception { | |
| DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); | |
| DocumentBuilder builder = factory.newDocumentBuilder(); | |
| return builder.parse(new ByteArrayInputStream(xmlContent.getBytes())); | |
| } | |
| public Document parseXML(String xmlContent) throws Exception { | |
| DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); | |
| factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); | |
| factory.setFeature("http://xml.org/sax/features/external-general-entities", false); | |
| factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); | |
| factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); | |
| factory.setXIncludeAware(false); | |
| factory.setExpandEntityReferences(false); | |
| DocumentBuilder builder = factory.newDocumentBuilder(); | |
| return builder.parse(new ByteArrayInputStream(xmlContent.getBytes())); | |
| } |
| public Document parseXML(String xmlContent) throws Exception { | ||
| DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); | ||
| DocumentBuilder builder = factory.newDocumentBuilder(); | ||
| return builder.parse(new ByteArrayInputStream(xmlContent.getBytes())); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Specify character encoding for XML parsing
The code should specify a character encoding when converting the XML string to bytes to avoid encoding issues.
-return builder.parse(new ByteArrayInputStream(xmlContent.getBytes()));
+return builder.parse(new ByteArrayInputStream(xmlContent.getBytes("UTF-8")));📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| return builder.parse(new ByteArrayInputStream(xmlContent.getBytes())); | |
| return builder.parse(new ByteArrayInputStream(xmlContent.getBytes("UTF-8"))); |
🤖 Prompt for AI Agents
In
xml_verification_/src/main/java/com/testsigma/addons/restapi/CompareXMLTextsIgnoringXPaths.java
around line 83, the call builder.parse(new
ByteArrayInputStream(xmlContent.getBytes())) uses the platform default encoding;
change it to explicitly specify a charset (e.g.,
xmlContent.getBytes(StandardCharsets.UTF_8)) or, better, parse from a
Reader/InputSource (new InputSource(new StringReader(xmlContent)) and optionally
setEncoding("UTF-8")) so the XML is consistently interpreted; add the necessary
import for StandardCharsets if you choose the first approach.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Review continued from previous batch...
| try{ | ||
| Connection connection = databaseUtil.getConnection(testData2.getValue().toString()); | ||
| Statement stmt = connection.createStatement(); | ||
| String query = testData1.getValue().toString(); | ||
| ResultSet resultSet = stmt.executeQuery(query); | ||
| int columnNo = resultSet.getMetaData().getColumnCount(); | ||
| int count = 0; | ||
| while (resultSet.next()) { | ||
| for (int i = 1; i <= columnNo; i++) { | ||
| String columnValue = resultSet.getString(i); | ||
| if(columnValue != null) | ||
| { | ||
| if(columnValue.contains(testData3.getValue().toString())) | ||
| { | ||
| count++; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| if(count >= 1) | ||
| { | ||
| sb.append("<br>The output from the Query is matching with expected value."); | ||
| sb.append("<br>Expected value:"+testData3.getValue().toString()); | ||
| setSuccessMessage(sb.toString()); | ||
| logger.info(sb.toString()); | ||
| } | ||
| else | ||
| { | ||
| result = Result.FAILED; | ||
| sb.append("The selected query value not match with expected rows:" + "<br>"); | ||
| sb.append("Expected value :"+testData3.getValue().toString() + "<br>"); | ||
| setErrorMessage(sb.toString()); | ||
| logger.warn(sb.toString()); | ||
| } | ||
|
|
||
| } | ||
| catch (Exception e){ | ||
| String errorMessage = ExceptionUtils.getStackTrace(e); | ||
| result = Result.FAILED; | ||
| setErrorMessage(errorMessage); | ||
| logger.warn(errorMessage); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Add resource cleanup to prevent connection leaks
Database resources (Connection, Statement, ResultSet) are not being closed after use, which will lead to resource leaks.
Add proper resource management:
public Result execute() throws NoSuchElementException {
Result result = Result.SUCCESS;
logger.info("Initiating execution" + "<br>");
DatabaseUtil databaseUtil = new DatabaseUtil();
+ Connection connection = null;
+ Statement stmt = null;
+ ResultSet resultSet = null;
try{
- Connection connection = databaseUtil.getConnection(testData2.getValue().toString());
- Statement stmt = connection.createStatement();
+ connection = databaseUtil.getConnection(testData2.getValue().toString());
+ stmt = connection.createStatement();
String query = testData1.getValue().toString();
- ResultSet resultSet = stmt.executeQuery(query);
+ resultSet = stmt.executeQuery(query);
// ... rest of the code
}
catch (Exception e){
String errorMessage = ExceptionUtils.getStackTrace(e);
result = Result.FAILED;
setErrorMessage(errorMessage);
logger.warn(errorMessage);
}
+ finally {
+ // Close resources in finally block
+ try {
+ if (resultSet != null) resultSet.close();
+ if (stmt != null) stmt.close();
+ if (connection != null) connection.close();
+ } catch (SQLException se) {
+ logger.warn("Error closing resources: " + se.getMessage());
+ }
+ }
return result;
}🤖 Prompt for AI Agents
In mssqldb_queries/src/main/java/com/testsigma/addons/restapi/MSSqlValidate.java
around lines 37 to 78, the ResultSet, Statement and Connection are not closed
which can leak DB resources; update the method to use try-with-resources (or a
finally block) so ResultSet, Statement and Connection are closed reliably after
use, ensuring any exceptions are handled and errors still set result and
messages as before; prefer try-with-resources around creation of
Connection/Statement/ResultSet, remove manual close in happy path, and
log/propagate any close failures consistently.
| try{ | ||
| Connection connection = databaseUtil.getConnection(testData2.getValue().toString()); | ||
| Statement stmt = connection.createStatement(); | ||
| String query = testData1.getValue().toString(); | ||
| ResultSet resultSet = stmt.executeQuery(query); | ||
| ResultSetMetaData rsmd = resultSet.getMetaData(); | ||
| int columnNo = resultSet.getMetaData().getColumnCount(); | ||
| sb.append("Successfully Executed Select Query and Resultset is : " + "<br>"); | ||
| for (int i = 1; i <= columnNo; i++) { | ||
| sb.append(rsmd.getColumnName(i)); | ||
| sb.append(", "); | ||
| } | ||
| sb.append("<br>"); | ||
| while (resultSet.next()) { | ||
| for (int j = 1; j <= columnNo; j++) { | ||
| if (j > 1) sb.append(", "); | ||
| String columnValue = resultSet.getString(j); | ||
| if (resultSet.wasNull()) { | ||
| sb.append(""); | ||
| } | ||
| sb.append(columnValue); | ||
| } | ||
| sb.append("<br>"); | ||
| } | ||
| setSuccessMessage(sb.toString()); | ||
| logger.info(sb.toString()); | ||
| } | ||
| catch (Exception e){ | ||
| String errorMessage = ExceptionUtils.getStackTrace(e); | ||
| result = com.testsigma.sdk.Result.FAILED; | ||
| setErrorMessage(errorMessage); | ||
| logger.warn(errorMessage); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Add resource cleanup to prevent connection leaks
Database resources (Connection, Statement, ResultSet) are not being closed after use, which will lead to resource leaks.
Declare resources outside try and close them in a finally block:
public com.testsigma.sdk.Result execute() throws NoSuchElementException {
Result result = Result.SUCCESS;
logger.info("Initiating execution");
DatabaseUtil databaseUtil = new DatabaseUtil();
+ Connection connection = null;
+ Statement stmt = null;
+ ResultSet resultSet = null;
try{
- Connection connection = databaseUtil.getConnection(testData2.getValue().toString());
- Statement stmt = connection.createStatement();
+ connection = databaseUtil.getConnection(testData2.getValue().toString());
+ stmt = connection.createStatement();
String query = testData1.getValue().toString();
- ResultSet resultSet = stmt.executeQuery(query);
+ resultSet = stmt.executeQuery(query);
// ... rest of the code
}
catch (Exception e){
String errorMessage = ExceptionUtils.getStackTrace(e);
result = com.testsigma.sdk.Result.FAILED;
setErrorMessage(errorMessage);
logger.warn(errorMessage);
}
+ finally {
+ // Close resources in finally block
+ try {
+ if (resultSet != null) resultSet.close();
+ if (stmt != null) stmt.close();
+ if (connection != null) connection.close();
+ } catch (SQLException se) {
+ logger.warn("Error closing resources: " + se.getMessage());
+ }
+ }
return result;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try{ | |
| Connection connection = databaseUtil.getConnection(testData2.getValue().toString()); | |
| Statement stmt = connection.createStatement(); | |
| String query = testData1.getValue().toString(); | |
| ResultSet resultSet = stmt.executeQuery(query); | |
| ResultSetMetaData rsmd = resultSet.getMetaData(); | |
| int columnNo = resultSet.getMetaData().getColumnCount(); | |
| sb.append("Successfully Executed Select Query and Resultset is : " + "<br>"); | |
| for (int i = 1; i <= columnNo; i++) { | |
| sb.append(rsmd.getColumnName(i)); | |
| sb.append(", "); | |
| } | |
| sb.append("<br>"); | |
| while (resultSet.next()) { | |
| for (int j = 1; j <= columnNo; j++) { | |
| if (j > 1) sb.append(", "); | |
| String columnValue = resultSet.getString(j); | |
| if (resultSet.wasNull()) { | |
| sb.append(""); | |
| } | |
| sb.append(columnValue); | |
| } | |
| sb.append("<br>"); | |
| } | |
| setSuccessMessage(sb.toString()); | |
| logger.info(sb.toString()); | |
| } | |
| catch (Exception e){ | |
| String errorMessage = ExceptionUtils.getStackTrace(e); | |
| result = com.testsigma.sdk.Result.FAILED; | |
| setErrorMessage(errorMessage); | |
| logger.warn(errorMessage); | |
| } | |
| public com.testsigma.sdk.Result execute() throws NoSuchElementException { | |
| Result result = Result.SUCCESS; | |
| logger.info("Initiating execution"); | |
| DatabaseUtil databaseUtil = new DatabaseUtil(); | |
| Connection connection = null; | |
| Statement stmt = null; | |
| ResultSet resultSet = null; | |
| try { | |
| connection = databaseUtil.getConnection(testData2.getValue().toString()); | |
| stmt = connection.createStatement(); | |
| String query = testData1.getValue().toString(); | |
| resultSet = stmt.executeQuery(query); | |
| ResultSetMetaData rsmd = resultSet.getMetaData(); | |
| int columnNo = rsmd.getColumnCount(); | |
| sb.append("Successfully Executed Select Query and Resultset is : ").append("<br>"); | |
| for (int i = 1; i <= columnNo; i++) { | |
| sb.append(rsmd.getColumnName(i)).append(", "); | |
| } | |
| sb.append("<br>"); | |
| while (resultSet.next()) { | |
| for (int j = 1; j <= columnNo; j++) { | |
| if (j > 1) sb.append(", "); | |
| String columnValue = resultSet.getString(j); | |
| if (resultSet.wasNull()) { | |
| sb.append(""); | |
| } | |
| sb.append(columnValue); | |
| } | |
| sb.append("<br>"); | |
| } | |
| setSuccessMessage(sb.toString()); | |
| logger.info(sb.toString()); | |
| } catch (Exception e) { | |
| String errorMessage = ExceptionUtils.getStackTrace(e); | |
| result = com.testsigma.sdk.Result.FAILED; | |
| setErrorMessage(errorMessage); | |
| logger.warn(errorMessage); | |
| } finally { | |
| try { | |
| if (resultSet != null) resultSet.close(); | |
| if (stmt != null) stmt.close(); | |
| if (connection != null) connection.close(); | |
| } catch (SQLException se) { | |
| logger.warn("Error closing resources: " + se.getMessage()); | |
| } | |
| } | |
| return result; | |
| } |
🤖 Prompt for AI Agents
In mssqldb_queries/src/main/java/com/testsigma/addons/web/MSSqlselect.java
around lines 36 to 68, the Connection, Statement and ResultSet are created
inside the try and never closed, causing potential connection leaks; refactor to
declare Connection, Statement and ResultSet variables before the try and ensure
they are closed in a finally block (or better, use try-with-resources) after
use, handling possible nulls and SQLExceptions during close, and move
setSuccessMessage/logger calls to the try so cleanup always runs regardless of
success or failure.
| try{ | ||
| Connection connection = databaseUtil.getConnection(testData2.getValue().toString()); | ||
| Statement stmt = connection.createStatement(); | ||
| String query = testData1.getValue().toString(); | ||
| ResultSet resultSet = stmt.executeQuery(query); | ||
| ResultSetMetaData rsmd = resultSet.getMetaData(); | ||
| int columnNo = resultSet.getMetaData().getColumnCount(); | ||
| sb.append("Successfully Executed Select Query and Resultset is : " + "<br>"); | ||
| for (int i = 1; i <= columnNo; i++) { | ||
| sb.append(rsmd.getColumnName(i)); | ||
| sb.append(", "); | ||
| } | ||
| sb.append("<br>"); | ||
| while (resultSet.next()) { | ||
| for (int j = 1; j <= columnNo; j++) { | ||
| if (j > 1) sb.append(", "); | ||
| String columnValue = resultSet.getString(j); | ||
| if (resultSet.wasNull()) { | ||
| sb.append(""); | ||
| } | ||
| sb.append(columnValue); | ||
| } | ||
| sb.append("<br>"); | ||
| } | ||
| setSuccessMessage(sb.toString()); | ||
| logger.info(sb.toString()); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Resource leak: JDBC resources not properly closed.
The code doesn't close the Connection, Statement, or ResultSet, which can lead to resource leaks.
Apply this diff to add proper resource management:
+ Connection connection = null;
+ Statement stmt = null;
+ ResultSet resultSet = null;
+
try{
- Connection connection = databaseUtil.getConnection(testData2.getValue().toString());
- Statement stmt = connection.createStatement();
+ connection = databaseUtil.getConnection(testData2.getValue().toString());
+ stmt = connection.createStatement();
String query = testData1.getValue().toString();
- ResultSet resultSet = stmt.executeQuery(query);
+ resultSet = stmt.executeQuery(query);
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnNo = rsmd.getColumnCount();And add a finally block after the catch block:
}
catch (Exception e){
String errorMessage = ExceptionUtils.getStackTrace(e);
result = Result.FAILED;
setErrorMessage(errorMessage);
logger.warn(errorMessage);
}
+ finally {
+ // Close resources
+ try {
+ if (resultSet != null) resultSet.close();
+ if (stmt != null) stmt.close();
+ if (connection != null) connection.close();
+ } catch (Exception e) {
+ logger.warn("Error closing resources: " + e.getMessage());
+ }
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try{ | |
| Connection connection = databaseUtil.getConnection(testData2.getValue().toString()); | |
| Statement stmt = connection.createStatement(); | |
| String query = testData1.getValue().toString(); | |
| ResultSet resultSet = stmt.executeQuery(query); | |
| ResultSetMetaData rsmd = resultSet.getMetaData(); | |
| int columnNo = resultSet.getMetaData().getColumnCount(); | |
| sb.append("Successfully Executed Select Query and Resultset is : " + "<br>"); | |
| for (int i = 1; i <= columnNo; i++) { | |
| sb.append(rsmd.getColumnName(i)); | |
| sb.append(", "); | |
| } | |
| sb.append("<br>"); | |
| while (resultSet.next()) { | |
| for (int j = 1; j <= columnNo; j++) { | |
| if (j > 1) sb.append(", "); | |
| String columnValue = resultSet.getString(j); | |
| if (resultSet.wasNull()) { | |
| sb.append(""); | |
| } | |
| sb.append(columnValue); | |
| } | |
| sb.append("<br>"); | |
| } | |
| setSuccessMessage(sb.toString()); | |
| logger.info(sb.toString()); | |
| Connection connection = null; | |
| Statement stmt = null; | |
| ResultSet resultSet = null; | |
| try { | |
| connection = databaseUtil.getConnection(testData2.getValue().toString()); | |
| stmt = connection.createStatement(); | |
| String query = testData1.getValue().toString(); | |
| resultSet = stmt.executeQuery(query); | |
| ResultSetMetaData rsmd = resultSet.getMetaData(); | |
| int columnNo = rsmd.getColumnCount(); | |
| sb.append("Successfully Executed Select Query and Resultset is : " + "<br>"); | |
| for (int i = 1; i <= columnNo; i++) { | |
| sb.append(rsmd.getColumnName(i)); | |
| sb.append(", "); | |
| } | |
| sb.append("<br>"); | |
| while (resultSet.next()) { | |
| for (int j = 1; j <= columnNo; j++) { | |
| if (j > 1) sb.append(", "); | |
| String columnValue = resultSet.getString(j); | |
| if (resultSet.wasNull()) { | |
| sb.append(""); | |
| } | |
| sb.append(columnValue); | |
| } | |
| sb.append("<br>"); | |
| } | |
| setSuccessMessage(sb.toString()); | |
| logger.info(sb.toString()); | |
| } catch (Exception e) { | |
| String errorMessage = ExceptionUtils.getStackTrace(e); | |
| result = Result.FAILED; | |
| setErrorMessage(errorMessage); | |
| logger.warn(errorMessage); | |
| } finally { | |
| // Close resources | |
| try { | |
| if (resultSet != null) resultSet.close(); | |
| if (stmt != null) stmt.close(); | |
| if (connection != null) connection.close(); | |
| } catch (Exception e) { | |
| logger.warn("Error closing resources: " + e.getMessage()); | |
| } | |
| } |
🤖 Prompt for AI Agents
In mssqldb_queries/src/main/java/com/testsigma/addons/web/MsSqlSelectIOS.java
around lines 35 to 60, the try block opens a Connection, Statement and ResultSet
but never closes them; update the method to properly manage JDBC resources by
using try-with-resources for Connection, Statement and ResultSet (preferred) or,
if not possible, ensure a finally block after the catch closes resultSet, stmt
and connection in reverse order with null checks and individual try/catch around
each close to avoid suppressing exceptions; keep existing logging and
setSuccessMessage behavior but move resource creation into the
try-with-resources header (or add the finally block) so no JDBC resources leak.
| if (resultSet.wasNull()) { | ||
| sb.append(""); | ||
| } | ||
| sb.append(columnValue); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Logic issue in null value handling.
The code checks resultSet.wasNull() after getting a string value, but then appends an empty string and then still appends the columnValue. This will result in the actual value being appended even when it's null.
Apply this diff to fix the null handling logic:
String columnValue = resultSet.getString(j);
if (resultSet.wasNull()) {
- sb.append("");
+ sb.append("NULL");
+ } else {
+ sb.append(columnValue);
}
- sb.append(columnValue);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (resultSet.wasNull()) { | |
| sb.append(""); | |
| } | |
| sb.append(columnValue); | |
| String columnValue = resultSet.getString(j); | |
| if (resultSet.wasNull()) { | |
| sb.append("NULL"); | |
| } else { | |
| sb.append(columnValue); | |
| } |
🤖 Prompt for AI Agents
In mssqldb_queries/src/main/java/com/testsigma/addons/web/MsSqlSelectIOS.java
around lines 52 to 55, the code calls resultSet.getString(...) then checks
resultSet.wasNull() but still appends columnValue afterwards, causing nulls to
be treated as real values; change the logic to append either an empty string or
the columnValue based on the wasNull() check (i.e. if resultSet.wasNull() append
"" else append columnValue), avoiding appending both.
| while (resultSet.next()) { | ||
| for (int i = 1; i <= columnNo; i++) { | ||
| String columnValue = resultSet.getString(i); | ||
| if(columnValue != null) | ||
| { | ||
| if(columnValue.contains(testData3.getValue().toString())) | ||
| { | ||
| count++; | ||
| } | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Resource leak: JDBC resources not properly closed.
The code doesn't close the Connection, Statement, or ResultSet, which can lead to resource leaks and potential database connection pool exhaustion.
Apply this diff to add proper resource management:
+ Connection connection = null;
+ Statement stmt = null;
+ ResultSet resultSet = null;
+
try{
- Connection connection = databaseUtil.getConnection(testData2.getValue().toString());
- Statement stmt = connection.createStatement();
+ connection = databaseUtil.getConnection(testData2.getValue().toString());
+ stmt = connection.createStatement();
String query = testData1.getValue().toString();
- ResultSet resultSet = stmt.executeQuery(query);
+ resultSet = stmt.executeQuery(query);
int columnNo = resultSet.getMetaData().getColumnCount();
int count = 0;
while (resultSet.next()) {
for (int i = 1; i <= columnNo; i++) {
String columnValue = resultSet.getString(i);
if(columnValue != null)
{
if(columnValue.contains(testData3.getValue().toString()))
{
count++;
}
}
}
}And add a finally block after the catch block:
}
catch (Exception e){
String errorMessage = ExceptionUtils.getStackTrace(e);
result = com.testsigma.sdk.Result.FAILED;
setErrorMessage(errorMessage);
logger.warn(errorMessage);
}
+ finally {
+ // Close resources
+ try {
+ if (resultSet != null) resultSet.close();
+ if (stmt != null) stmt.close();
+ if (connection != null) connection.close();
+ } catch (Exception e) {
+ logger.warn("Error closing resources: " + e.getMessage());
+ }
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| while (resultSet.next()) { | |
| for (int i = 1; i <= columnNo; i++) { | |
| String columnValue = resultSet.getString(i); | |
| if(columnValue != null) | |
| { | |
| if(columnValue.contains(testData3.getValue().toString())) | |
| { | |
| count++; | |
| } | |
| } | |
| } | |
| } | |
| Connection connection = null; | |
| Statement stmt = null; | |
| ResultSet resultSet = null; | |
| try { | |
| connection = databaseUtil.getConnection(testData2.getValue().toString()); | |
| stmt = connection.createStatement(); | |
| String query = testData1.getValue().toString(); | |
| resultSet = stmt.executeQuery(query); | |
| int columnNo = resultSet.getMetaData().getColumnCount(); | |
| int count = 0; | |
| while (resultSet.next()) { | |
| for (int i = 1; i <= columnNo; i++) { | |
| String columnValue = resultSet.getString(i); | |
| if (columnValue != null) { | |
| if (columnValue.contains(testData3.getValue().toString())) { | |
| count++; | |
| } | |
| } | |
| } | |
| } | |
| } | |
| catch (Exception e) { | |
| String errorMessage = ExceptionUtils.getStackTrace(e); | |
| result = com.testsigma.sdk.Result.FAILED; | |
| setErrorMessage(errorMessage); | |
| logger.warn(errorMessage); | |
| } | |
| finally { | |
| // Close resources | |
| try { | |
| if (resultSet != null) resultSet.close(); | |
| if (stmt != null) stmt.close(); | |
| if (connection!= null) connection.close(); | |
| } catch (Exception e) { | |
| logger.warn("Error closing resources: " + e.getMessage()); | |
| } | |
| } |
🤖 Prompt for AI Agents
In mssqldb_queries/src/main/java/com/testsigma/addons/web/MSSqlValidate.java
around lines 46 to 57 the ResultSet (and likely its Statement and Connection)
are not closed, causing resource leaks; update the method to manage JDBC
resources properly by either using try-with-resources for the Connection,
Statement/PreparedStatement and ResultSet so they are auto-closed, or if not
possible wrap the existing logic in try { ... } catch (SQLException e) { ... }
finally { if (resultSet != null) try { resultSet.close(); } catch (SQLException
ex) { log error } if (statement != null) try { statement.close(); } catch
(SQLException ex) { log error } if (connection != null) try {
connection.close(); } catch (SQLException ex) { log error } } ensuring null
checks and logging any SQLException thrown during close.
| baseFile = File.createTempFile("baseXml_", ".xml"); | ||
| actualFile = File.createTempFile("actualXml_", ".xml"); | ||
| logger.info("Created temporary base file: " + baseFile.getAbsolutePath()); | ||
| logger.info("Created temporary actual file: " + actualFile.getAbsolutePath()); | ||
|
|
||
| // Use the utility to handle potential URLs or local paths | ||
| baseFile = urlToFileConverter(filePath1); | ||
| actualFile = urlToFileConverter(filePath2); | ||
| logger.info("Prepared base & actual file content."); | ||
|
|
||
| // Ensure temp files are deleted on exit (redundant if urlToFileConverter does it, but safe) | ||
| baseFile.deleteOnExit(); | ||
| actualFile.deleteOnExit(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Redundant temporary file creation and incorrect variable reassignment
Similar to the web version, temporary files are created but then immediately overwritten. Additionally, the deleteOnExit() calls after reassignment might not affect the originally created temp files.
-// 2. Convert URLs/Paths to Temporary Files
-baseFile = File.createTempFile("baseXml_", ".xml");
-actualFile = File.createTempFile("actualXml_", ".xml");
-logger.info("Created temporary base file: " + baseFile.getAbsolutePath());
-logger.info("Created temporary actual file: " + actualFile.getAbsolutePath());
-
-// Use the utility to handle potential URLs or local paths
-baseFile = urlToFileConverter(filePath1);
-actualFile = urlToFileConverter(filePath2);
-logger.info("Prepared base & actual file content.");
-
-// Ensure temp files are deleted on exit (redundant if urlToFileConverter does it, but safe)
-baseFile.deleteOnExit();
-actualFile.deleteOnExit();
+// 2. Convert URLs/Paths to Temporary Files
+// Use the utility to handle potential URLs or local paths
+baseFile = urlToFileConverter(filePath1);
+actualFile = urlToFileConverter(filePath2);
+logger.info("Prepared base file: " + baseFile.getAbsolutePath());
+logger.info("Prepared actual file: " + actualFile.getAbsolutePath());
+
+// Ensure temp files are deleted on exit
+baseFile.deleteOnExit();
+actualFile.deleteOnExit();📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| baseFile = File.createTempFile("baseXml_", ".xml"); | |
| actualFile = File.createTempFile("actualXml_", ".xml"); | |
| logger.info("Created temporary base file: " + baseFile.getAbsolutePath()); | |
| logger.info("Created temporary actual file: " + actualFile.getAbsolutePath()); | |
| // Use the utility to handle potential URLs or local paths | |
| baseFile = urlToFileConverter(filePath1); | |
| actualFile = urlToFileConverter(filePath2); | |
| logger.info("Prepared base & actual file content."); | |
| // Ensure temp files are deleted on exit (redundant if urlToFileConverter does it, but safe) | |
| baseFile.deleteOnExit(); | |
| actualFile.deleteOnExit(); | |
| // 2. Convert URLs/Paths to Temporary Files | |
| // Use the utility to handle potential URLs or local paths | |
| baseFile = urlToFileConverter(filePath1); | |
| actualFile = urlToFileConverter(filePath2); | |
| logger.info("Prepared base file: " + baseFile.getAbsolutePath()); | |
| logger.info("Prepared actual file: " + actualFile.getAbsolutePath()); | |
| // Ensure temp files are deleted on exit | |
| baseFile.deleteOnExit(); | |
| actualFile.deleteOnExit(); |
🤖 Prompt for AI Agents
In
xml_verification_/src/main/java/com/testsigma/addons/restapi/CompareLocalXMLFiles.java
around lines 76 to 88, the code creates temp files then immediately overwrites
those variables with urlToFileConverter results, making the initial
createTempFile calls redundant and causing deleteOnExit() to apply to the wrong
File objects; remove the initial File.createTempFile(...) calls and their logger
lines, call urlToFileConverter(filePath1/2) directly into baseFile/actualFile,
null-check the returned File objects, and call deleteOnExit() (and log their
paths) on the File instances returned by urlToFileConverter so the correct files
are cleaned up.
| setSuccessMessage(String.format("<b>The given XML files are equal</b> (considering ignored XPaths).", | ||
| filePath1, filePath2)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
String formatting error with missing placeholders
The success message uses String.format but doesn't include placeholders for the file paths.
-setSuccessMessage(String.format("<b>The given XML files are equal</b> (considering ignored XPaths).",
- filePath1, filePath2));
+setSuccessMessage("<b>The given XML files are equal</b> (considering ignored XPaths).");📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| setSuccessMessage(String.format("<b>The given XML files are equal</b> (considering ignored XPaths).", | |
| filePath1, filePath2)); | |
| setSuccessMessage("<b>The given XML files are equal</b> (considering ignored XPaths)."); |
🤖 Prompt for AI Agents
In
xml_verification_/src/main/java/com/testsigma/addons/restapi/CompareLocalXMLFiles.java
around lines 112-113, the call to String.format supplies filePath1 and filePath2
but the format string has no placeholders; update the format string to include
placeholders (e.g. "<b>The given XML files are equal</b> (considering ignored
XPaths): %s and %s") and pass filePath1 and filePath2, or alternatively remove
String.format and build the message without extra args—ensure the final
setSuccessMessage call uses a format string that matches the supplied arguments.
| public File urlToFileConverter(String url) throws IOException, Exception { | ||
| logger.info("url: " + url); | ||
| if (url.startsWith("https://")) { | ||
| logger.info("Given is s3 url ...File name:"); | ||
| URL urlObject = new URL(url); | ||
| File tempFile = File.createTempFile("tempXMLFile_", "." + "xml"); | ||
| logger.info("created temporary file: " + tempFile.getAbsolutePath()); | ||
| FileUtils.copyURLToFile(urlObject, tempFile); | ||
| logger.info("Temp file created with name for s3 file" + tempFile.getName() | ||
| + " at path " + tempFile.getAbsolutePath()); | ||
| return tempFile; | ||
| } else { | ||
| // Ignoring " and ' from file path... | ||
| url = url.replaceAll("[\"']", ""); | ||
| logger.info("Given is local file path.. Creating temp file"); | ||
| File tempFile = File.createTempFile("tempLocalFile_", new File(url).getName()); | ||
| FileUtils.copyFile(new File(url), tempFile); | ||
| logger.info("Temp file created for local file with name " + tempFile.getName() | ||
| + " at path " + tempFile.getAbsolutePath()); | ||
| return tempFile; | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Security concern: Potential path traversal vulnerability
The urlToFileConverter method accepts user input and creates files without properly validating or sanitizing the file paths. This could allow path traversal attacks if malicious input like ../../sensitive/file is provided.
Add path validation to prevent directory traversal:
public File urlToFileConverter(String url) throws IOException, Exception {
logger.info("url: " + url);
if (url.startsWith("https://")) {
logger.info("Given is s3 url ...File name:");
URL urlObject = new URL(url);
File tempFile = File.createTempFile("tempXMLFile_", "." + "xml");
logger.info("created temporary file: " + tempFile.getAbsolutePath());
FileUtils.copyURLToFile(urlObject, tempFile);
logger.info("Temp file created with name for s3 file" + tempFile.getName()
+ " at path " + tempFile.getAbsolutePath());
return tempFile;
} else {
// Ignoring " and ' from file path...
url = url.replaceAll("[\"']", "");
+
+ // Validate the file path to prevent directory traversal
+ File file = new File(url);
+ if (!file.exists()) {
+ throw new IOException("File does not exist: " + url);
+ }
+ if (!file.isFile()) {
+ throw new IOException("Path is not a file: " + url);
+ }
+ // Ensure the path is within expected boundaries (optional, based on requirements)
+ String canonicalPath = file.getCanonicalPath();
+
logger.info("Given is local file path.. Creating temp file");
- File tempFile = File.createTempFile("tempLocalFile_", new File(url).getName());
- FileUtils.copyFile(new File(url), tempFile);
+ File tempFile = File.createTempFile("tempLocalFile_", file.getName());
+ FileUtils.copyFile(file, tempFile);
logger.info("Temp file created for local file with name " + tempFile.getName()
+ " at path " + tempFile.getAbsolutePath());
return tempFile;
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public File urlToFileConverter(String url) throws IOException, Exception { | |
| logger.info("url: " + url); | |
| if (url.startsWith("https://")) { | |
| logger.info("Given is s3 url ...File name:"); | |
| URL urlObject = new URL(url); | |
| File tempFile = File.createTempFile("tempXMLFile_", "." + "xml"); | |
| logger.info("created temporary file: " + tempFile.getAbsolutePath()); | |
| FileUtils.copyURLToFile(urlObject, tempFile); | |
| logger.info("Temp file created with name for s3 file" + tempFile.getName() | |
| + " at path " + tempFile.getAbsolutePath()); | |
| return tempFile; | |
| } else { | |
| // Ignoring " and ' from file path... | |
| url = url.replaceAll("[\"']", ""); | |
| logger.info("Given is local file path.. Creating temp file"); | |
| File tempFile = File.createTempFile("tempLocalFile_", new File(url).getName()); | |
| FileUtils.copyFile(new File(url), tempFile); | |
| logger.info("Temp file created for local file with name " + tempFile.getName() | |
| + " at path " + tempFile.getAbsolutePath()); | |
| return tempFile; | |
| } | |
| } | |
| public File urlToFileConverter(String url) throws IOException, Exception { | |
| logger.info("url: " + url); | |
| if (url.startsWith("https://")) { | |
| logger.info("Given is s3 url ...File name:"); | |
| URL urlObject = new URL(url); | |
| File tempFile = File.createTempFile("tempXMLFile_", "." + "xml"); | |
| logger.info("created temporary file: " + tempFile.getAbsolutePath()); | |
| FileUtils.copyURLToFile(urlObject, tempFile); | |
| logger.info("Temp file created with name for s3 file" + tempFile.getName() | |
| + " at path " + tempFile.getAbsolutePath()); | |
| return tempFile; | |
| } else { | |
| // Ignoring " and ' from file path... | |
| url = url.replaceAll("[\"']", ""); | |
| // Validate the file path to prevent directory traversal | |
| File file = new File(url); | |
| if (!file.exists()) { | |
| throw new IOException("File does not exist: " + url); | |
| } | |
| if (!file.isFile()) { | |
| throw new IOException("Path is not a file: " + url); | |
| } | |
| // Ensure the path is within expected boundaries (optional, based on requirements) | |
| String canonicalPath = file.getCanonicalPath(); | |
| logger.info("Given is local file path.. Creating temp file"); | |
| File tempFile = File.createTempFile("tempLocalFile_", file.getName()); | |
| FileUtils.copyFile(file, tempFile); | |
| logger.info("Temp file created for local file with name " + tempFile.getName() | |
| + " at path " + tempFile.getAbsolutePath()); | |
| return tempFile; | |
| } | |
| } |
🤖 Prompt for AI Agents
In
xml_verification_/src/main/java/com/testsigma/addons/restapi/CompareLocalXMLFiles.java
around lines 160 to 181, the urlToFileConverter method directly uses the
incoming url/local path to read and create temp files which permits path
traversal and unsafe file creation; canonicalize the provided path and validate
it against an allowed base directory (or a whitelist) before using it: resolve
new File(url).getCanonicalPath(), compute the canonical path of the allowed base
(or temp directory) and ensure the target path startsWith that base, reject or
throw a checked exception if it does not, and do not use the user-supplied
filename as the temp file suffix—use a safe fixed suffix (e.g., ".xml") and a
generated prefix instead; also sanitize inputs by stripping dangerous sequences,
handle malformed urls safely, and log only safe path info.
| if (currentXPath.equals(trimmedPrefix) || currentXPath.startsWith(trimmedPrefix + "/")) { | ||
| return true; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Potential XPath matching issue
The XPath matching logic checks if the path equals the prefix OR starts with prefix + "/". This might miss cases where you want to ignore all attributes of an element. For example, ignoring /root/element won't ignore /root/element/@attribute.
Consider enhancing the matching logic to handle different XPath patterns:
String trimmedPrefix = prefix.trim();
if (currentXPath.equals(trimmedPrefix) || currentXPath.startsWith(trimmedPrefix + "/")) {
return true;
}
+// Also check if we're trying to ignore all attributes of an element
+if (currentXPath.startsWith(trimmedPrefix + "/@")) {
+ return true;
+}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (currentXPath.equals(trimmedPrefix) || currentXPath.startsWith(trimmedPrefix + "/")) { | |
| return true; | |
| if (currentXPath.equals(trimmedPrefix) || currentXPath.startsWith(trimmedPrefix + "/")) { | |
| return true; | |
| } | |
| // Also check if we're trying to ignore all attributes of an element | |
| if (currentXPath.startsWith(trimmedPrefix + "/@")) { | |
| return true; | |
| } |
🤖 Prompt for AI Agents
In
xml_verification_/src/main/java/com/testsigma/addons/restapi/CompareLocalXMLFiles.java
around lines 447-448, the XPath match only checks equality or
startsWith(trimmedPrefix + "/"), which can miss attribute forms like
"/root/element/@attr" or variants without the extra slash; update the condition
to also treat attribute and predicate forms as matches by additionally checking
startsWith(trimmedPrefix + "/@"), startsWith(trimmedPrefix + "@"), and
startsWith(trimmedPrefix + "[") (or other element-specific variants you need),
so attributes and common XPath variations under the prefix are correctly treated
as covered.
| setSuccessMessage(String.format("<b>The given XML files are equal</b> (considering ignored XPaths).", | ||
| filePath1, filePath2)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
String formatting error with missing placeholders
The success message uses String.format but doesn't include placeholders for the file paths that were likely intended to be displayed.
-setSuccessMessage(String.format("<b>The given XML files are equal</b> (considering ignored XPaths).",
- filePath1, filePath2));
+setSuccessMessage("<b>The given XML files are equal</b> (considering ignored XPaths).");Or if you want to include the file paths:
-setSuccessMessage(String.format("<b>The given XML files are equal</b> (considering ignored XPaths).",
- filePath1, filePath2));
+setSuccessMessage(String.format("<b>The given XML files '%s' and '%s' are equal</b> (considering ignored XPaths).",
+ filePath1, filePath2));📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| setSuccessMessage(String.format("<b>The given XML files are equal</b> (considering ignored XPaths).", | |
| filePath1, filePath2)); | |
| setSuccessMessage(String.format("<b>The given XML files '%s' and '%s' are equal</b> (considering ignored XPaths).", | |
| filePath1, filePath2)); |
🤖 Prompt for AI Agents
In
xml_verification_/src/main/java/com/testsigma/addons/web/CompareLocalXMLFiles.java
around lines 109-110, the call to String.format builds a success message but the
format string contains no %s placeholders for filePath1 and filePath2; either
add appropriate placeholders into the format string (e.g. "<b>The given XML
files are equal</b> (considering ignored XPaths): %s and %s") and pass
filePath1, filePath2 as arguments, or remove String.format and construct the
message directly using concatenation; ensure the placeholders match the argument
order and that nulls are handled if necessary.
Addon Name: Rest API Utils
Jarvis Link: https://jarvis.testsigma.com/ui/tenants/3072/addons
Addon Name: mysql_queries
Addon Name: MsSQLDB_Queries
Addon Name: Substring_Removebylength
Addon Name: SQL Server Queries
Addon Name: XML Verification
Jarvis Link: https://jarvis.testsigma.com/ui/tenants/2817/addons
Jira : https://testsigma.atlassian.net/browse/TE-29132
Added already present addons to rest api application
Summary by CodeRabbit