Below are list of frequently used commands. This would come very handy while working with docker & kubernetes.
Thursday, 23 September 2021
Thursday, 12 August 2021
How to create and execute Jmeter script using Java
Performance Test!. When we say this term, one of the first things that gets into our mind is 'Jmeter'.
Jmeter is the go-to tool for the performance testing needs in open source community. It is built completely using Java, designed to perform load test and measure performance. It can simulate load on a server, group of servers, network to check the threshold limit and analyze performance under different types of loads. Vast list of plug-ins which extends jmeter capabilities and making it handle most of the performance test requirements.
Mostly the Jmeter GUI is used to create the scripts, configure the users, capture other details and execute the scripts. But, when it comes to integrate the performance tests to code driven automation frameworks, one has to switch to Jmeter GUI to create scripts & fallback to framework to execute the jmeter scripts. In order to make the integration seamless, Jmeter scripts can be created & executed during runtime using code driven framework. Below code snippet would lead you to achieve the same.
Below snippet will let you create a jmeter script (jmx) for a webservice by adding minimal elements to test plan. Typical hierarchy of a web request in a jmx would be as below:
Test Plan à Thread Group à Sampler à Assertions à Listeners
Steps:
- Create a maven project through eclipse or any IDE.
- Add the below Jmeter dependencies in your POM file:
- ApacheJMeter_core
- ApacheJMeter_components
- ApacheJMeter_http
- jorphan
- ApacheJMeter_java
- Create a class named "APITest" and copy the below code snippet
- Change the service details & file locations accordingly.
- DONE..! You are all set to create and run the jmeter script from java.
import java.io.File; import java.io.FileOutputStream; import org.apache.commons.io.FileUtils; 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.report.config.ConfigurationException; import org.apache.jmeter.report.dashboard.ReportGenerator; 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; public class APITest { public void createAndExecute() { File jmeterHome = new File("C:/apache-jmeter"); try { if (jmeterHome.exists()) { // JMeter Engine StandardJMeterEngine jmeter = new StandardJMeterEngine(); setconfig(jmeterHome, "./htmlreportsdir"); // JMeter Test Plan, basic all u JOrphan HashTree HashTree testPlanTree = new HashTree(); // HTTP Sampler HTTPSamplerProxy httpSampler = new HTTPSamplerProxy(); httpSampler.setName("HTTP Sampler"); httpSampler.setProtocol("https"); httpSampler.setDomain("testjmeter.com"); httpSampler.setPort(8080); httpSampler.setPath("/getservicepath"); httpSampler.setMethod("GET"); httpSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName()); httpSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName()); httpSampler.setEnabled(true); httpSampler.addArgument("Arg1","val1");//Arguments httpSampler.addArgument("Arg1","val1");//Arguments httpSampler.addNonEncodedArgument("", "serviceBody", "=");//payload httpSampler.setPostBodyRaw(true); //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("API Thread Group"); threadGroup.setNumThreads(20); //Users threadGroup.setRampUp(10); //Seconds threadGroup.setSamplerController(loopController); threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName()); threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName()); threadGroup.setIsSameUserOnNextIteration(true); threadGroup.setScheduler(false); //Test Plan TestPlan testPlan = new TestPlan("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(httpSampler); // save generated test plan to JMeter's .jmx file format String jmxFilePath = "./jmxfiles/TestAPI.jmx"; SaveService.saveTree(testPlanTree, new FileOutputStream(jmxFilePath)); // add Summarizer output to get test progress in stdout like: String jtlFilePath = ".jtlFiles/TestAPI.jtl"; ReportGenerator reportGenerator = setReportInfo(testPlanTree, jtlFilePath); //Run Test Plan jmeter.configure(testPlanTree); jmeter.run(); // Report Generator FileUtils.deleteDirectory(new File("./htmlreportsdir"));// delete old report FileUtils.deleteDirectory(new File("./reportsdir"));// delete old report reportGenerator.generate(); System.out.println("Test completed. See " + jtlFilePath + " file for results"); System.out.println("JMeter .jmx script is available at " + jmxFilePath); } else { System.out.println("Jmeter Home not found.."); } } catch (Exception e) { System.out.println(e.getMessage()); } } public void setconfig(File jmeterHome,String htmlrepDir){ File jmeterProperties = new File(jmeterHome.getPath() +"/bin/jmeter.properties"); //JMeter initialization (properties, log levels, locale, etc) JMeterUtils.setJMeterHome(jmeterHome.getPath()); JMeterUtils.loadJMeterProperties(jmeterProperties.getPath()); JMeterUtils.initLocale(); //Set directory for HTML report JMeterUtils.setProperty("jmeter.reportgenerator.exporter.html.property.output_dir",htmlrepDir); } public ReportGenerator setReportInfo(HashTree testPlanTree,String jtlFilePath) throws ConfigurationException{ 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 File logFile = new File(jtlFilePath); //delete log file if exists if (logFile.exists()){ boolean delete = logFile.delete(); System.out.println("Jtl deleted: " + delete); } //Summary Report ResultCollector logger = new ResultCollector(summer); logger.setEnabled(true); logger.setFilename(logFile.getPath()); //creating ReportGenerator for creating HTML report ReportGenerator reportGenerator = new ReportGenerator(jtlFilePath, logger); testPlanTree.add(testPlanTree.getArray()[0], logger); return reportGenerator; } }
Friday, 4 June 2021
How to establish a connection to Remote Host & Copy file
Many times we do get the requirement, to connect a remote server & perform operations like copying a file from local to remote, vice versa and many others. But, have you ever thought how do we do that through java.? Yes, We can. Java has multiple libraries which can perform this task. One such java library which can perform this task is Jcraft's 'JSch (Java Secure Channel)' .
Below example will let you know how to connect a remote host & perform copy operations.
public void copyFiletoRemotehost(String username,String pwd,String[] remotehosts, String port) { Session jschSession = null; int SESSION_TIMEOUT = 10000; final int CHANNEL_TIMEOUT = 5000; String REMOTE_HOST = ""; int REMOTE_PORT = 22; String lFile = "C:/localhost/local.txt"; String rFile = "/localtoRemote.txt"; try { JSch jsch = new JSch(); for(int i=0; i < remotehosts.length; i++) { REMOTE_HOST = remotehosts[i].toString(); jschSession = jsch.getSession(username, REMOTE_HOST, REMOTE_PORT); //Remove known_hosts requirement java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); jschSession.setConfig(config); //authenticate using password jschSession.setPassword(pwd); jschSession.connect(SESSION_TIMEOUT); Channel sftp = jschSession.openChannel("sftp"); sftp.connect(CHANNEL_TIMEOUT); ChannelSftp channelSftp = (ChannelSftp) sftp; channelSftp.put(lFile, rFile); channelSftp.exit(); //Copy from one location to another with remote server copyFile(jschSession); jschSession.disconnect(); } } catch (JSchException | SftpException e) { e.printStackTrace(); } finally { if (jschSession != null) { jschSession.disconnect(); } } } /** * This method will let you copy from one folder to another within the remote server */ public static void copyFile(Session jschSession) throws JSchException { String cmd1 = "cp C:/username/localtoRemote.txt C:/anotherfolder/localtoRemote.txt"; Channel exec = jschSession.openChannel("exec"); ChannelExec channelExec = (ChannelExec) exec; channelExec.setCommand(cmd1); exec.connect(CHANNEL_TIMEOUT); channelExec.setErrStream(System.err); }References: