I created a jmx file using java code. But when i tried to execute the jmx file using java, it throws the exception. Pls help me.. I have added all the jars.
(Error in NonGUIDriver java.lang.IllegalArgumentException: Problem loading XML from:'/home/ksahu/MyScreenshots/k.jmx', conversion error com.thoughtworks.xstream.converters.ConversionException: null : null)
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.sampler.HTTPSampler;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import java.io.FileInputStream;
public class RunJMXfile {
public static void main(String[] argv) throws Exception {
// JMeter Engine
StandardJMeterEngine jmeter = new StandardJMeterEngine();
// Initialize Properties, logging, locale, etc.
JMeterUtils.loadJMeterProperties("/home/ksahu/apache-jmeter-2.13/bin/jmeter.properties");
JMeterUtils.setJMeterHome("/home/ksahu/apache-jmeter-2.13");
JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level
JMeterUtils.initLocale();
// Initialize JMeter SaveService
SaveService.loadProperties();
// Load existing .jmx Test Plan
FileInputStream in = new FileInputStream("/home/ksahu/MyScreenshots/k.jmx");
HashTree testPlanTree = SaveService.loadTree(in);
in.close();
// Run JMeter Test
jmeter.configure(testPlanTree);
jmeter.run();
}
}
This is the code that i have used to generate the jmx file
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.sampler.HTTPSampler;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.threads.SetupThreadGroup;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
public class jmeterTesting {
public static void main(String[] args) throws FileNotFoundException, IOException{
// Engine
StandardJMeterEngine jm = new StandardJMeterEngine();
JMeterUtils.setJMeterHome("/home/ksahu/apache-jmeter-2.13");
// jmeter.properties
JMeterUtils.loadJMeterProperties("/home/ksahu/apache-jmeter-2.13/bin/jmeter.properties");
HashTree hashTree = new HashTree();
// HTTP Sampler
HTTPSampler httpSampler = new HTTPSampler();
httpSampler.setDomain("www.google.com");
httpSampler.setPort(80);
httpSampler.setPath("/");
httpSampler.setMethod("GET");
// Loop Controller
TestElement loopCtrl = new LoopController();
((LoopController)loopCtrl).setLoops(1);
((LoopController)loopCtrl).addTestElement(httpSampler);
((LoopController)loopCtrl).setFirst(true);
// Thread Group
SetupThreadGroup threadGroup = new SetupThreadGroup();
threadGroup.setNumThreads(1);
threadGroup.setRampUp(1);
threadGroup.setSamplerController((LoopController)loopCtrl);
// Test plan
TestPlan testPlan = new TestPlan("MY TEST PLAN");
hashTree.add("testPlan", testPlan);
hashTree.add("loopCtrl", loopCtrl);
hashTree.add("threadGroup", threadGroup);
hashTree.add("httpSampler", httpSampler);
jm.configure(hashTree);
jm.run();
System.out.println(hashTree);
SaveService.saveTree(hashTree,new FileOutputStream("/home/ksahu/MyScreenshots/k.jmx"));
}
}
Try to open your /home/ksahu/MyScreenshots/k.jmx in JMeter GUI. If it does not open - there is a problem with the code, you generated the JMX file with. In that case update your question with the code, you used to create the k.jmx file.
See Chapter 4. RUN A JMETER TEST THROUGH A PROGRAM (FROM JAVA CODE) of the Five Ways To Launch a JMeter Test without Using the JMeter GUI for details.
Also there is a sample project which you can use as a reference: https://bitbucket.org/blazemeter/jmeter-from-code/
You need to change the text "org.apache.jorphan.collections.HashTree" in the JMX generated using java to "hashTree". Open the JMX in any text editor and do the replace as mentioned. If that doesn't suffice, include the below step.
You need to set TestElement.ENABLED, TestElement.TEST_CLASS and TestElement.GUI_CLASS explicitly for each element. For example a sampler can be defined as below.
HTTPSamplerProxy httpSampler = new HTTPSamplerProxy();
httpSampler.setDomain(DOMAIN);
httpSampler.setPort(PORT);
httpSampler.setPath(PATH);
httpSampler.setMethod(METHOD);
httpSampler.addArgument("", "${domain}");
httpSampler.setProperty(TestElement.ENABLED, true);
httpSampler.setResponseTimeout("20000");
httpSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
httpSampler .setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());
Related
I'm running a spring boot application and I'm trying to get the chromedriver not load from my local directory but rather from the project resources folder. I have my chromdriver.exe in resources/chromedriver.exe but I'm not sure how can I load it.
I tried this didn't work. Tried filepath to be "resources/chromedriver.exe" didn't work as well
String filePath = ClassLoader.getSystemClassLoader().getResource("resources/chromedriver.exe").getFile();
System.out.println(filePath);
System.setProperty("webdriver.chrome.driver", filePath)
If you are using Spring, you could try this:
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Resource resource = new ClassPathResource("chromedriver.exe");
String filePath = resource.getFile().getPath();
System.out.println(filePath);
System.setProperty("webdriver.chrome.driver", filePath);
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.junit.Test;
public class GettingStarted {
#Test
public void testGoogleSearch() throws InterruptedException {
// Optional. If not specified, WebDriver searches the PATH for chromedriver.
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com/");
Thread.sleep(5000); // Let the user actually see something!
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
Thread.sleep(5000); // Let the user actually see something!
driver.quit();
}
}
https://sites.google.com/a/chromium.org/chromedriver/getting-started
For example in Windows if chromedriver.exe is in C:/chromium use:
System.setProperty("webdriver.chrome.driver", "C:\\chromium\\chromedriver.exe");
I want to benchmark some remote API calls via code. I've been using JMH for it so far, but it doesnt quite fit my need as a stress test tool (JMH works well for micro benchmarking, where the snippet being benchmarks rusn really really fast). My remote APIs respond in tens of seconds, so I really need to run the tests with:
Multiple parameterized inputs
Multiple client threads (controlling the load)
I'm able achieve a lot via manual tests in JMeter UI, but I would like to write some java tests/benchmarks that use JMeter and does the same. Is there a way to do that?
You can either kick off an existing JMeter test or create a new one using JMeter API
Run existing test example code:
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import java.io.File;
public class RunExistingJMeterTest {
public static void main(String[] args) throws Exception {
// Initialize properties
JMeterUtils.loadJMeterProperties("/path/to/your/jmeter/bin/jmeter.properties");
// JMeter Engine
StandardJMeterEngine jmeter = new StandardJMeterEngine();
// Initialize logging, locale, etc.
JMeterUtils.setJMeterHome("/path/to/your/jmeter");
JMeterUtils.initLocale();
// Initialize JMeter SaveService
SaveService.loadProperties();
// Load existing .jmx Test Plan
HashTree testPlanTree = SaveService.loadTree(new File("/path/to/your/jmeter/extras/Test.jmx"));
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
// Store execution results into a .jtl file
String logFile = "/path/to/results/file.jtl";
ResultCollector logger = new ResultCollector(summer);
logger.setFilename(logFile);
testPlanTree.add(testPlanTree.getArray()[0], logger);
// Run JMeter Test
jmeter.configure(testPlanTree);
jmeter.run();
}
}
Create JMeter script programmatically:
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.config.gui.ArgumentsPanel;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.control.gui.LoopControlPanel;
import org.apache.jmeter.control.gui.TestPlanGui;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.control.gui.HttpTestSampleGui;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.threads.gui.ThreadGroupGui;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import java.io.FileOutputStream;
public class CreateNewJMeterTest {
public static void main(String[] args) throws Exception {
StandardJMeterEngine jmeter = new StandardJMeterEngine();
//JMeter initialization (properties, log levels, locale, etc)
JMeterUtils.setJMeterHome("/path/to/your/jmeter/installation");
JMeterUtils.loadJMeterProperties("/path/to/your/jmeter/bin/jmeter.properties");
JMeterUtils.initLocale();
// JMeter Test Plan, basically JOrphan HashTree
HashTree testPlanTree = new HashTree();
// First HTTP Sampler - open example.com
HTTPSamplerProxy examplecomSampler = new HTTPSamplerProxy();
examplecomSampler.setDomain("example.com");
examplecomSampler.setPort(80);
examplecomSampler.setPath("/");
examplecomSampler.setMethod("GET");
examplecomSampler.setName("Open example.com");
examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());
// Loop Controller
LoopController loopController = new LoopController();
loopController.setLoops(1);
loopController.setFirst(true);
loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());
loopController.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName());
loopController.initialize();
// Thread Group
ThreadGroup threadGroup = new ThreadGroup();
threadGroup.setName("Example Thread Group");
threadGroup.setNumThreads(1);
threadGroup.setRampUp(1);
threadGroup.setSamplerController(loopController);
threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());
threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());
// Test Plan
TestPlan testPlan = new TestPlan("Create JMeter Script From Java Code");
testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());
// Construct Test Plan from previously initialized elements
testPlanTree.add(testPlan);
HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
threadGroupHashTree.add(examplecomSampler);
// save generated test plan to JMeter's .jmx file format
SaveService.saveTree(testPlanTree, new FileOutputStream("/path/to/test.jmx"));
//add Summarizer output to get test progress in stdout like:
// summary = 2 in 1.3s = 1.5/s Avg: 631 Min: 290 Max: 973 Err: 0 (0.00%)
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
// Store execution results into a .jtl file
String logFile = "/path/to/test/results.jtl";
ResultCollector logger = new ResultCollector(summer);
logger.setFilename(logFile);
testPlanTree.add(testPlanTree.getArray()[0], logger);
// Run Test Plan
jmeter.configure(testPlanTree);
jmeter.run();
System.exit(0);
}
}
Check out Five Ways To Launch a JMeter Test without Using the JMeter GUI article for more information.
I am working on Jmeter Scripts from sometime now, there is a need to secure the Jmeter script and majorly make it unreadable for external stakeholders. My expectation is to obfuscate or deliver the script as some kind of JAR or executable. I need some ideas or workaround to start with.
Thanks
Senz79
It is possible to run existing JMeter script from Java code or create a JMeter test purely in Java using JMeter API so it is not a problem to create an executable binary which will run your test and obfuscate it.
Example Java code to run a JMeter test:
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import java.io.File;
public class JMeterFromCode {
public static void main(String[] argv) throws Exception {
// JMeter Engine
StandardJMeterEngine jmeter = new StandardJMeterEngine();
// Initialize Properties, logging, locale, etc.
JMeterUtils.loadJMeterProperties("/tmp/jmeter/bin/jmeter.properties");
JMeterUtils.setJMeterHome("/tmp/jmeter");
JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level
JMeterUtils.initLocale();
// Initialize JMeter SaveService
SaveService.loadProperties();
// Load existing .jmx Test Plan
HashTree testPlanTree = SaveService.loadTree(new File("/tmp/jmeter/test.jmx"));
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
ResultCollector logger = new ResultCollector(summer);
logger.setFilename("/tmp/jmeter/test.jtl");
testPlanTree.add(testPlanTree.getArray()[0], logger);
// Run JMeter Test
jmeter.configure(testPlanTree);
jmeter.run();
}
}
See the following reference material to get started:
Five Ways To Launch a JMeter Test without Using the JMeter GUI
Bytecode obfuscation
How can we trigger concurrent requests in JMeter...
I am not talking about the non -html elements (where we have a provision in jmeter to download them concurrently).
I have few AJAX calls to be downloaded concurrently...
As per JMeter 3.0 there is no suitable Test Elements, you will need to:
go for JSR223 Sampler + Groovy language and Apache HTTP Components (which are parts of JMeter anyway)
or develop your custom sampler to overcome JMeter thread group limitation and kick off extra threads to execute AJAX calls.
Example JSR223 Sampler Code:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; // necessary imports
List<String> urls = new ArrayList<String>(); // initialize array of URLs
Collections.addAll(urls,args); // read URLs from "Parameters" input and add them to array
ExecutorService pool = Executors.newFixedThreadPool(urls.size()); // initialize pool of Future Tasks with number of threads equal to size of URLs provided
for (String url : urls) { // for each URL from list
final String currentURL = url;
pool.submit(new Runnable() { // Sumbit a new thread which will execute GET request
#Override
public void run() {
try {
HttpClient client = new DefaultHttpClient(); // Use Apache Commons HTTPClient to perform GET request
HttpGet get = new HttpGet(currentURL);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
pool.shutdown(); // shut down thread pool
More details: How to Load Test AJAX/XHR Enabled Sites With JMeter
I am reading xlsx file by adding Beanshell Preprocessor. When i run code in Eclispe, it's working fine.
But when i run in Jmeter, i am getting below error. I have copied required jar files in Jmeter lib and lib\ext as well.
2015/06/08 14:53:04 ERROR - jmeter.util.BeanShellInterpreter: Error
invoking bsh method: eval
In file: inline evaluation of: import java.io.File; import
java.io.FileInputStream; import java.io.IOException; . . . ''
Encountered "=" at line 18, column 41. 2015/06/08 14:53:04 WARN -
jmeter.modifiers.BeanShellPreProcessor: Problem in BeanShell script
org.apache.jorphan.util.JMeterException: Error invoking bsh method:
eval In file: inline evaluation of: ``import java.io.File; import
java.io.FileInputStream; import java.io.IOException; . . . ''
Encountered "=" at line 18, column 41."
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class url {
public static void main(String[] args) throws IOException {
FileInputStream file=new FileInputStream(new File("C:\\temp\\project.xlsx"));
XSSFWorkbook workbook=new XSSFWorkbook(file);
XSSFSheet sheet=workbook.getSheetAt(0);
Iterator<Row>rowIterator=sheet.iterator();
int count=1;
while(rowIterator.hasNext()){
Row row=rowIterator.next();
Iterator<Cell> cellIterator=row.cellIterator();
while(cellIterator.hasNext()){
Cell cell=cellIterator.next();
String TextInCell=cell.toString();
String cellContent1="Cricket";
String cellContent2="Football";
String cellContent3="F1";
String cellContent4="Badminton";
String cellContent5="Misslenous";
if(TextInCell.contains(cellContent1)){
String var=cell.getRichStringCellValue().toString();
String Category = cellContent1;
}else if(TextInCell.contains(cellContent2)){
String var=cell.getRichStringCellValue().toString();
String Category = cellContent2;
}else if(TextInCell.contains(cellContent3)){
String var=cell.getRichStringCellValue().toString();
String Category = cellContent3;
}else if(TextInCell.contains(cellContent4)){
String var=cell.getRichStringCellValue().toString();
String Category = cellContent4;
System.out.println(var + "----"+Category );
}else{
String var=cell.getRichStringCellValue().toString();
String Category = cellContent5;
}
}
}
}
}
Beanshell is not very Java, you need to amend your code to match Beanshell conventions to wit:
remove "class" and "main" method
remove <Cell> from Iterator<Cell>
remove <Row> from Iterator<Row>
explicitly cast Objects like Row row=(Row)rowIterator.next();
Beanshell has well-known performance problems, if you need to deal with Excel files I would recommend going for JSR223 PreProcessor and "groovy" language instead. To enable "groovy" support just download groovy-all.jar and drop it to the /lib folder of your JMeter installation
JMeter restart is required to pick up groovy or POI or whatever jars.
See How to Extract Data From Files With JMeter guide for more information on dealing with binary files, hopefully you'll get some clues.