79504114

Date: 2025-03-12 15:49:37
Score: 0.5
Natty:
Report link

Is this from array defined before in groovy script or array from the system or properties file?

Here is example script that I use where I am using map structure to read parameters from file.

Named parameters work better.

import org.apache.jmeter.threads.JMeterContextService
import org.apache.jmeter.threads.JMeterVariables
import java.nio.file.*
import org.apache.jmeter.util.JMeterUtils
import java.text.SimpleDateFormat
import java.nio.file.Paths

// Function to clean SQL query by replacing newlines with spaces and removing extra spaces
String cleanQuery(String query) {
    return query.replaceAll("[\r\n]+", " ").replaceAll("\s+", " ").trim()
}



// Function to substitute placeholders in the query with provided values
String substitutePlaceholders(String query, Map<String, String> properties) {
    properties.each { key, value ->
        if (key != "query") { // Skip the query key itself
            query = query.replace("\$" + key, value) // Simple string replacement instead of regex
        }
    }
    return query
}


// Function to generate jtl results filename
String generateResultsFilename(String sqlFilePath) {
    
    // Get current timestamp in the format hhmmss_MMDDYYYY
    String timestamp = new SimpleDateFormat("HHmmss_MMddyyyy").format(new Date())

    if (sqlFilePath == null || sqlFilePath.trim().isEmpty()) {
        throw new IllegalArgumentException("SQL file path is empty or not provided.")
    }

    // Extract only the filename (without path)
    String fileName = Paths.get(sqlFilePath).getFileName().toString()    
    String pathName = Paths.get(sqlFilePath).getParent().toString();

    // replace file extension
    String baseName = fileName.replaceAll(/\.[^.]*$/, ".jtl")
    
    // Construct the new filename
    return pathName + "\\results\\" + timestamp + "_" + baseName
}


// Retrieve the file name parameter from JMeter properties
String fileName = JMeterUtils.getPropDefault("SQL_FILE", "C:\\Tools\\JMT\\sqlqueries\\one.txt")


if (fileName == null || fileName.trim().isEmpty()) {
    throw new IllegalArgumentException("SQL file name is not provided in JMeter properties under 'SQL_FILE'")
}

try {
    // Read file contents
    String fileContent = new String(Files.readAllBytes(Paths.get(fileName)), "UTF-8").trim()
    
    // Split by semicolon
    List<String> parts = fileContent.split(";")
    
    if (parts.size() < 2) {
        throw new IllegalArgumentException("File format incorrect. Ensure it contains a query followed by parameter assignments.")
    }

    // Extract query with placeholders
    String query = parts[0].trim()

    // Extract parameters into a map
    Map<String, String> paramMap = parts[1..-1].collectEntries { entry ->
        def pair = entry.split("=", 2)
        pair.length == 2 ? [(pair[0].trim()): pair[1].trim()] : [:]
    }

    // Replace placeholders with corresponding values
    paramMap.each { key, value ->
        query = query.replace("\$" + key, value)
    }

    // Clean the query
    query = cleanQuery(query)
    log.info("cleaned query=" + query)

    // Store final query in JMeter variable
    vars.put("SQL_QUERY", query)

    log.info("Processed SQL Query: " + query)

    log.info("SQL query successfully loaded and cleaned from file: " + fileName)

    // create name for results file 
    String resultsFile = generateResultsFilename(fileName)

    // Store it in a JMeter variable
    vars.put("TARGET_JTL", resultsFile)
    log.info("JTL Results will be stored file: " + resultsFile)

    JMeterUtils.setProperty("TARGET_JTL", resultsFile)

} catch (Exception e) {
    log.error("Error processing SQL file: " + fileName, e)
    throw new RuntimeException("Failed to process SQL file", e)
}



    
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Starts with a question (0.5): Is this
  • Low reputation (1):
Posted by: Gajendra Shete