Skip to content

Instantly share code, notes, and snippets.

@svillarreal
Last active April 5, 2024 20:34
Show Gist options
  • Save svillarreal/5eb90a66b8972633b95c249abb3566da to your computer and use it in GitHub Desktop.
Save svillarreal/5eb90a66b8972633b95c249abb3566da to your computer and use it in GitHub Desktop.
JMeter as Code - Programmatic approach - Stress Test
package com.company.stresstest.oauth;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
/**
* @author Santiago Villarreal
*/
public class AuthorizationService {
private static final String GRANT_TYPE_PASSWORD = "password";
private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationService.class);
public static final String AUTHORIZATION_HEADER_VALUE = "Authorization Header Value";
public static TokenInfo getTokenForClientCredentials(String username, String password, String url ) throws Exception {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add(HttpHeaders.AUTHORIZATION, AUTHORIZATION_HEADER_VALUE);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("username", username);
map.add("password", password);
map.add("grant_type", GRANT_TYPE_PASSWORD);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
TokenInfo result = null;
if ( response.getStatusCode() == HttpStatus.OK ) {
String token = response.getBody();
ObjectMapper mapper = new ObjectMapper();
result = mapper.readValue(token, TokenInfo.class);
}
else {
LOGGER.error("Error received from request: " + response);
}
return result;
}
}
package com.company.stresstest.samples;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy;
/**
* @author Santiago Villarreal
*/
public class HttpSamples {
public static final String DEV_DOMAIN = "erer3ggbgdfsdf.execute-api.us-west-2.amazonaws.com";
public static final String DEV_ENV = "dev";
public static HTTPSamplerProxy load() {
HTTPSamplerProxy httpSampler = new HTTPSamplerProxy();
httpSampler.setDomain(DEV_DOMAIN);
httpSampler.setPort(443);
httpSampler.setPath("/" + DEV_ENV + "/path/to/env");
httpSampler.setMethod("POST");
httpSampler.setName("Load Dev");
httpSampler.setFollowRedirects(false);
httpSampler.setProtocol("https");
httpSampler.addNonEncodedArgument("", "{\"document\":\"0323604000184\"}", "");
httpSampler.setPostBodyRaw(true);
return httpSampler;
}
}
package com.company.stresstest;
import com.company.stresstest.samples.HttpSamples;
import com.company.stresstest.util.Utils;
import org.apache.jmeter.assertions.DurationAssertion;
import org.apache.jmeter.assertions.ResponseAssertion;
import org.apache.jmeter.assertions.AssertionResult;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import java.io.File;
import java.io.FileOutputStream;
/**
* @author Santiago Villarreal
*/
public class Main {
private static final String CSV_LOG_FILE_NAME = "stresstest.csv";
private static final String REPORT_FOLDER = "HTMLReports";
private static final int THREADS_NUMBER = 100;
private static final int LOOPS_NUMBER = 10;
public static void main(String[] args) throws Exception {
Main.initialize();
// JMeter Test Plan
HashTree testPlanTree = new HashTree();
TestPlan testPlan = new TestPlan("Stress test");
testPlan.setEnabled(true);
HeaderManager headerManager = Utils.buildHeaders();
// Build Test Plan from previously initialized elements
testPlanTree.add(testPlan);
ThreadGroup threadGroup = Utils.buildThreadGroupWithLoop(LOOPS_NUMBER, THREADS_NUMBER, "Inbound List tests");
HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
//What we test
DurationAssertion durationAssertion = new DurationAssertion();
durationAssertion.setName("Duration Assertion 3s per request");
durationAssertion.setAllowedDuration(3000);
ResponseAssertion responseAssertion = new ResponseAssertion();
responseAssertion.setTestFieldResponseCode();
responseAssertion.setToContainsType();
responseAssertion.addTestString("200|302");
HTTPSamplerProxy samplerProxy = HttpSamples.load();
threadGroupHashTree.add(samplerProxy, headerManager);
threadGroupHashTree.add(samplerProxy, durationAssertion);
threadGroupHashTree.add(samplerProxy, responseAssertion);
//Generate the JMX
SaveService.saveTree(testPlanTree, new FileOutputStream("stresstest.jmx"));
ResultCollector jMeterSummarizer = Utils.buildJMeterSummarizer(CSV_LOG_FILE_NAME);
testPlanTree.add(testPlan, jMeterSummarizer);
// Run the Test Plan
StandardJMeterEngine jmeterEngine = buildJMeterEngine(testPlanTree);
System.out.println("Running test suite, please wait...\n");
jmeterEngine.run();
System.out.println("\n... Test suite has finished.");
//We generate the HTML Report
//Runtime.getRuntime().exec("/../bin/jmeter -g stresstest.csv -o " + REPORT_FOLDER);
ReportGenerator generator = new ReportGenerator("stresstest.csv", null);
generator.generate();
}
private static StandardJMeterEngine buildJMeterEngine(HashTree testPlanTree) {
StandardJMeterEngine jmeterEngine = new StandardJMeterEngine();
jmeterEngine.configure(testPlanTree);
return jmeterEngine;
}
private static void initialize() throws Exception {
System.out.println("########## INITIALIZING #############");
//JMeterUtils.loadJMeterProperties();
Runtime rt = Runtime.getRuntime();
Process rmExec = rt.exec("rm -r " + REPORT_FOLDER);
synchronized (rmExec) {
rmExec.wait(2000);
}
File file = new File(CSV_LOG_FILE_NAME);
if (file.exists()) {
file.delete();
}
File reportDir = new File(REPORT_FOLDER);
if (reportDir.exists()) {
throw new Exception(" #### Please delete " + REPORT_FOLDER + " folder #### ");
}
JMeterUtils.setJMeterHome(Main.class.getClassLoader().getResource(".").getPath());
JMeterUtils.loadJMeterProperties(Main.class.getClassLoader().getResource("bin/jmeter.properties").getPath());
JMeterUtils.initLocale();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.company.tresstest</groupId>
<artifactId>stresstest</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<jmeter.version>5.0</jmeter.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.jmeter/jorphan -->
<dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>jorphan</artifactId>
<version>${jmeter.version}</version>
</dependency>
<dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>ApacheJMeter_core</artifactId>
<version>${jmeter.version}</version>
</dependency>
<dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>ApacheJMeter_java</artifactId>
<version>${jmeter.version}</version>
</dependency>
<dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>ApacheJMeter_http</artifactId>
<version>${jmeter.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.8.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.company.stresstest.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
################################################################################
# Apache JMeter Property file for Report Generator
################################################################################
## Licensed to the Apache Software Foundation (ASF) under one or more
## contributor license agreements. See the NOTICE file distributed with
## this work for additional information regarding copyright ownership.
## The ASF licenses this file to You under the Apache License, Version 2.0
## (the "License"); you may not use this file except in compliance with
## the License. You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
################################################################################
#
# THIS FILE SHOULD NOT BE MODIFIED
#
# This avoids having to re-apply the modifications when upgrading JMeter
# Instead only user.properties should be modified:
# 1/ copy the property you want to modify to user.properties from here
# 2/ Change its value there
#
################################################################################
#---------------------------------------------------------------------------
# Reporting configuration
#---------------------------------------------------------------------------
# Sets the satisfaction threshold for the APDEX calculation (in milliseconds).
#jmeter.reportgenerator.apdex_satisfied_threshold=500
# Sets the tolerance threshold for the APDEX calculation (in milliseconds).
#jmeter.reportgenerator.apdex_tolerated_threshold=1500
# Sets satisfaction and tolerance threshold to specific samples.
# Use sample names or regular expression.
# Format is : sample_name:satisfaction|tolerance[;]
# Notice the colon between sample name and values, the pipe between thresholds and the
# semicolon at the end to separate different samples. Don't forget to escape after
# semicolon to span multiple lines. Ex :
#jmeter.reportgenerator.apdex_per_transaction=sample(\\d+):1000|2000,\
# samples12:3000|4000;\
# scenar01-12:5000|6000
# This property is used by menu item "Export transactions for report"
# It is used to select which transactions by default will be exported
#jmeter.reportgenerator.exported_transactions_pattern=[a-zA-Z0-9_\\-{}\\$\\.]*[-_][0-9]*
# Regular Expression which Indicates which samples to keep for graphs and statistics generation.
# Empty value means no filtering
#jmeter.reportgenerator.sample_filter=
# Sets the temporary directory used by the generation process if it needs file I/O operations.
#jmeter.reportgenerator.temp_dir=temp
# Sets the size of the sliding window used by percentile evaluation.
# Caution : higher value provides a better accuracy but needs more memory.
#jmeter.reportgenerator.statistic_window = 20000
# Configure this property to change the report title
#jmeter.reportgenerator.report_title=Apache JMeter Dashboard
# Default format
#jmeter.reportgenerator.date_format=yyyyMMddHHmmss
# Used to generate a report based on a date range
# If jmeter.save.saveservice.timestamp_format does not contain year
# then use 1970 as year
# Date range start date as per format declared in jmeter.reportgenerator.date_format
#jmeter.reportgenerator.start_date=
# Date range end date as per format declared in jmeter.reportgenerator.date_format
#jmeter.reportgenerator.end_date=
# Defines the overall granularity for over time graphs
# Granularity must be higher than 1000 (1second) otherwise Throughput graphs will be incorrect
# see Bug 60149
jmeter.reportgenerator.overall_granularity=60000
# Exclude transaction controller from analysis
# true by default
jmeter.reportgenerator.exclude_tc_from_top5_errors_by_sampler=true
# Response Time Percentiles graph definition
jmeter.reportgenerator.graph.responseTimePercentiles.classname=org.apache.jmeter.report.processor.graph.impl.ResponseTimePercentilesGraphConsumer
jmeter.reportgenerator.graph.responseTimePercentiles.title=Response Time Percentiles
# Response Time Distribution graph definition
jmeter.reportgenerator.graph.responseTimeDistribution.classname=org.apache.jmeter.report.processor.graph.impl.ResponseTimeDistributionGraphConsumer
jmeter.reportgenerator.graph.responseTimeDistribution.title=Response Time Distribution
jmeter.reportgenerator.graph.responseTimeDistribution.property.set_granularity=100
# Active Threads Over Time graph definition
jmeter.reportgenerator.graph.activeThreadsOverTime.classname=org.apache.jmeter.report.processor.graph.impl.ActiveThreadsGraphConsumer
jmeter.reportgenerator.graph.activeThreadsOverTime.title=Active Threads Over Time
jmeter.reportgenerator.graph.activeThreadsOverTime.property.set_granularity=${jmeter.reportgenerator.overall_granularity}
# Time VS Threads graph definition
jmeter.reportgenerator.graph.timeVsThreads.classname=org.apache.jmeter.report.processor.graph.impl.TimeVSThreadGraphConsumer
jmeter.reportgenerator.graph.timeVsThreads.title=Time VS Threads
# Bytes Throughput Over Time graph definition
jmeter.reportgenerator.graph.bytesThroughputOverTime.classname=org.apache.jmeter.report.processor.graph.impl.BytesThroughputGraphConsumer
jmeter.reportgenerator.graph.bytesThroughputOverTime.title=Bytes Throughput Over Time
jmeter.reportgenerator.graph.bytesThroughputOverTime.exclude_controllers=true
jmeter.reportgenerator.graph.bytesThroughputOverTime.property.set_granularity=${jmeter.reportgenerator.overall_granularity}
# Response Time Over Time graph definition
jmeter.reportgenerator.graph.responseTimesOverTime.classname=org.apache.jmeter.report.processor.graph.impl.ResponseTimeOverTimeGraphConsumer
jmeter.reportgenerator.graph.responseTimesOverTime.title=Response Time Over Time
jmeter.reportgenerator.graph.responseTimesOverTime.property.set_granularity=${jmeter.reportgenerator.overall_granularity}
# Percentiles Response Times over time
jmeter.reportgenerator.graph.responseTimePercentilesOverTime.classname=org.apache.jmeter.report.processor.graph.impl.ResponseTimePercentilesOverTimeGraphConsumer
jmeter.reportgenerator.graph.responseTimePercentilesOverTime.title=Response Time Percentiles Over Time (successful requests only)
jmeter.reportgenerator.graph.responseTimePercentilesOverTime.property.set_granularity=${jmeter.reportgenerator.overall_granularity}
# Synthetic Response Time Distribution
jmeter.reportgenerator.graph.syntheticResponseTimeDistribution.classname=org.apache.jmeter.report.processor.graph.impl.SyntheticResponseTimeDistributionGraphConsumer
jmeter.reportgenerator.graph.syntheticResponseTimeDistribution.title=Synthetic Response Times Distribution
jmeter.reportgenerator.graph.syntheticResponseTimeDistribution.exclude_controllers=true
jmeter.reportgenerator.graph.syntheticResponseTimeDistribution.property.set_satisfied_threshold=${jmeter.reportgenerator.apdex_satisfied_threshold}
jmeter.reportgenerator.graph.syntheticResponseTimeDistribution.property.set_tolerated_threshold=${jmeter.reportgenerator.apdex_tolerated_threshold}
# Latencies Over Time graph definition
jmeter.reportgenerator.graph.latenciesOverTime.classname=org.apache.jmeter.report.processor.graph.impl.LatencyOverTimeGraphConsumer
jmeter.reportgenerator.graph.latenciesOverTime.title=Latencies Over Time
jmeter.reportgenerator.graph.latenciesOverTime.property.set_granularity=${jmeter.reportgenerator.overall_granularity}
# Connect Time Over Time graph definition
jmeter.reportgenerator.graph.connectTimeOverTime.classname=org.apache.jmeter.report.processor.graph.impl.ConnectTimeOverTimeGraphConsumer
jmeter.reportgenerator.graph.connectTimeOverTime.title=Connect Time Over Time
jmeter.reportgenerator.graph.connectTimeOverTime.property.set_granularity=${jmeter.reportgenerator.overall_granularity}
# Response Time Vs Request graph definition
jmeter.reportgenerator.graph.responseTimeVsRequest.classname=org.apache.jmeter.report.processor.graph.impl.ResponseTimeVSRequestGraphConsumer
jmeter.reportgenerator.graph.responseTimeVsRequest.title=Response Time Vs Request
jmeter.reportgenerator.graph.responseTimeVsRequest.exclude_controllers=true
jmeter.reportgenerator.graph.responseTimeVsRequest.property.set_granularity=${jmeter.reportgenerator.overall_granularity}
# Latencies Vs Request graph definition
jmeter.reportgenerator.graph.latencyVsRequest.classname=org.apache.jmeter.report.processor.graph.impl.LatencyVSRequestGraphConsumer
jmeter.reportgenerator.graph.latencyVsRequest.title=Latencies Vs Request
jmeter.reportgenerator.graph.latencyVsRequest.exclude_controllers=true
jmeter.reportgenerator.graph.latencyVsRequest.property.set_granularity=${jmeter.reportgenerator.overall_granularity}
# Hits Per Second graph definition
jmeter.reportgenerator.graph.hitsPerSecond.classname=org.apache.jmeter.report.processor.graph.impl.HitsPerSecondGraphConsumer
jmeter.reportgenerator.graph.hitsPerSecond.title=Hits Per Second
jmeter.reportgenerator.graph.hitsPerSecond.exclude_controllers=true
jmeter.reportgenerator.graph.hitsPerSecond.property.set_granularity=${jmeter.reportgenerator.overall_granularity}
# Codes Per Second graph definition
jmeter.reportgenerator.graph.codesPerSecond.classname=org.apache.jmeter.report.processor.graph.impl.CodesPerSecondGraphConsumer
jmeter.reportgenerator.graph.codesPerSecond.title=Codes Per Second
jmeter.reportgenerator.graph.codesPerSecond.exclude_controllers=true
jmeter.reportgenerator.graph.codesPerSecond.property.set_granularity=${jmeter.reportgenerator.overall_granularity}
# Total TPS Per Second graph definition
jmeter.reportgenerator.graph.totalTPS.classname=org.apache.jmeter.report.processor.graph.impl.TotalTPSGraphConsumer
jmeter.reportgenerator.graph.totalTPS.title=Total Transactions Per Second
jmeter.reportgenerator.graph.totalTPS.property.set_granularity=${jmeter.reportgenerator.overall_granularity}
# Transactions Per Second graph definition
jmeter.reportgenerator.graph.transactionsPerSecond.classname=org.apache.jmeter.report.processor.graph.impl.TransactionsPerSecondGraphConsumer
jmeter.reportgenerator.graph.transactionsPerSecond.title=Transactions Per Second
jmeter.reportgenerator.graph.transactionsPerSecond.property.set_granularity=${jmeter.reportgenerator.overall_granularity}
# HTML Export
jmeter.reportgenerator.exporter.html.classname=org.apache.jmeter.report.dashboard.HtmlTemplateExporter
# Sets the source directory of templated files from which the html pages are generated.
#jmeter.reportgenerator.exporter.html.property.template_dir=report-template
# Sets the destination directory for generated html pages.
# This will be overridden by the command line option -o
#jmeter.reportgenerator.exporter.html.property.output_dir=report-output
# Regular Expression which Indicates which graph series are filtered in display
# Empty value means no filtering
#jmeter.reportgenerator.exporter.html.series_filter=
# Indicates whether series filter apply only on sample series or to all series
# setting this to false can lead to empty graphs if series_filter does not
# contain required series
#jmeter.reportgenerator.exporter.html.filters_only_sample_series=true
# Indicates whether only controller samples are displayed on graphs that support it.
#jmeter.reportgenerator.exporter.html.show_controllers_only=false
jmeter.reportgenerator.temp_dir=/Users/user/dev/jmeter/temp
jmeter.reportgenerator.exporter.html.property.output_dir=/Users/user/dev/jmeter/reports
jmeter.reportgenerator.exporter.html.property.template_dir=/Users/user/dev/jmeter/html-report-template
jmeter.save.saveservice.bytes=true
jmeter.save.saveservice.label=true
jmeter.save.saveservice.latency=true
jmeter.save.saveservice.response_code=true
jmeter.save.saveservice.response_message=true
jmeter.save.saveservice.successful=true
jmeter.save.saveservice.thread_counts=true
jmeter.save.saveservice.thread_name=true
jmeter.save.saveservice.time=true
jmeter.save.saveservice.print_field_names=true
# the timestamp format must include the time and should include the date.
# For example the default, which is milliseconds since the epoch:
#jmeter.save.saveservice.timestamp_format = ms
# Or the following would also be suitable
jmeter.save.saveservice.timestamp_format=dd/MM/yyyy HH:mm
#save service assertion
jmeter.save.saveservice.assertion_results_failure_message=true
jmeter.reportgenerator.sample_filter=.*
jmeter.reportgenerator.exporter.html.series_filter=.*
package com.company.stresstest.oauth;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author Santiago Villarreal
*/
public class TokenInfo {
@JsonProperty(value = "access_token")
private String accessToken;
@JsonProperty(value = "refresh_token")
private String refreshToken;
@JsonProperty(value = "token_type")
private String tokenType;
@JsonProperty(value = "expires_in")
private Long expiresIn;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getTokenType() {
return tokenType;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public Long getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(Long expiresIn) {
this.expiresIn = expiresIn;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("TokenInfo{");
sb.append("accessToken='").append(accessToken).append('\'');
sb.append("refreshToken='").append(refreshToken).append('\'');
sb.append(", tokenType='").append(tokenType).append('\'');
sb.append(", expiresIn=").append(expiresIn);
sb.append('}');
return sb.toString();
}
}
package com.company.stresstest.util;
import com.company.stresstest.oauth.AuthorizationService;
import com.company.stresstest.oauth.TokenInfo;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.http.gui.HeaderPanel;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.util.JMeterUtils;
/**
* @author Santiago Villarreal
*/
public class Utils {
public static HeaderManager buildHeaders() {
String hash = null;
String pingAuthorizationUrl = "https://company.com/oauth2";
String username = "username";
String password = "password";
try {
TokenInfo tokenInfo = AuthorizationService.getTokenForClientCredentials(username, password, pingAuthorizationUrl);
hash = tokenInfo.getAccessToken();
} catch (Exception e) {
e.printStackTrace();
}
String header = "Bearer " + hash;
System.out.println("########## " + header);
HeaderManager manager = new HeaderManager();
manager.add(new Header("Authorization", header));
manager.add(new Header("Content-Type", "application/json"));
manager.setName("Browser-derived headers");
manager.setProperty(TestElement.TEST_CLASS, HeaderManager.class.getName());
manager.setProperty(TestElement.GUI_CLASS, HeaderPanel.class.getName());
return manager;
}
public static ThreadGroup buildThreadGroupWithLoop(int loops, int threads, String name) {
// Loop Controller
LoopController loopController = new LoopController();
loopController.setLoops(loops);
loopController.setFirst(true);
loopController.initialize();
// Thread Group
ThreadGroup threadGroup = new ThreadGroup();
threadGroup.setName(name);
threadGroup.setNumThreads(threads);
threadGroup.setRampUp(1);
threadGroup.setEnabled(true);
threadGroup.setSamplerController(loopController);
return threadGroup;
}
public static ResultCollector buildJMeterSummarizer(String logFileName) {
// add Summarizer output to get progress in stdout:
Summariser summariser = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summariser = new Summariser(summariserName);
}
summariser.setEnabled(true);
// Store execution results into a .csv file
ResultCollector resultCollector = new ResultCollector(summariser);
resultCollector.setFilename(logFileName);
resultCollector.setEnabled(true);
// resultCollector.setErrorLogging(true);
return resultCollector;
}
}
@krishnaAutomation
Copy link

krishnaAutomation commented Feb 15, 2020

Hi Santiago Villarreal. Thanks For a wonderful project, I just imported this project. All jars downloaded, But once i am running the main class i am getting Editor does not contain main type. Could you please help to run this project. A veru very thanks in advance

@krishnaAutomation
Copy link

I have build the project successfully While running the main class i am getting this error. Could you please help me. ########## INITIALIZING #############
Exception in thread "main" java.io.IOException: Cannot run program "rm": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at kmeter2.Main.initialize(Main.java:94)
at kmeter2.Main.main(Main.java:34)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 6 more

@rabelenda
Copy link

Hello, you might check jmeter-java-dsl for a shorter syntax.

@anasoid
Copy link

anasoid commented Jun 10, 2021

you can use jmeter as code jmeter-as-code as wrapper to build Jmeter test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment