Tuesday, March 2, 2010

Playing with load - Jmeter

Scenario:
I want to test http web service using distinct samples as it violates primary key constraints on my database.

The solution:
Java Custom Sampler can be easily configured in jmeter by:
1. Implementing JavaSamplerClient interface.
2. Copy this custom jar into [JMETRE_HOME]/lib/ext . Also any related jars if required!
3. Fire up jmeter client. > Thread Group >Add > Sampler > Java Request ..You should see your custom sampler..

The code is below:
public class CustomServiceSampler implements JavaSamplerClient {
public Arguments getDefaultParameters() {
		Arguments params = new Arguments();
		params.addArgument("SERVICE_URI", DEFAULT_SERVICE_URI);
        params.addArgument("XML_TEMPLATE_PATH", DEFAULT_BRANCH_TEMPLATE_PATH);
        params.addArgument("DATA_ENCODING", DEFAULT_DATA_ENCODING);
		return params;
	}

	@Override
	public SampleResult runTest(JavaSamplerContext context) {
		SampleResult result = new SampleResult();
		
		HttpClient client = new HttpClient();
		String url = context.getParameter("SERVICE_URI", DEFAULT_SERVICE_URI);
		String templatePath= context.getParameter("XML_TEMPLATE_PATH", DEFAULT_BRANCH_TEMPLATE_PATH);
		String contentType= context.getParameter("DATA_ENCODING", DEFAULT_DATA_ENCODING);
		
		PostMethod method = new PostMethod(url);
		method.setRequestHeader("Content-Type", contentType);
		try {
			String template = FileUtils.readFileToString(new File(templatePath));
			String id= (System.currentTimeMillis() + "").substring(0, 10);
			result.setSampleLabel("Post xml- " + id);
			logger.info("Sending POST request to "+url +" with id:"+id);
			String xml = template.replaceAll("\\{ID\\}", branchId);
			xml = xml .replaceAll("\\{DATE\\}", new Date() + "");

			RequestEntity requestEntity = new StringRequestEntity(xml );
			method.setRequestEntity(requestEntity);

			result.setRequestHeaders(ToStringBuilder.reflectionToString(method.getRequestHeaders()));
			result.setSamplerData(xml );
			
			result.sampleStart();
			client.executeMethod(method);
			result.sampleEnd();
			
			String response = new String(method.getResponseBody());
			int code = method.getStatusCode();
			logger.info("Recived response .. status code "+code +" response xml :"+response);
			boolean success= code ==201 ? true:false;
			result.setSuccessful(success);
			result.setResponseData(response);
			result.setResponseCode(code+"");
			result.setResponseMessage(response);
			
			
		} catch (Exception e) {
			logger.error(e,e);
			result.sampleEnd();
			result.setResponseMessage(e.getMessage());
			result.setSuccessful(false);
		}
		return result;
	}
}

References:
http://www.scribd.com/doc/23029283/Using-JMeter-to-Performance-Test-Web-Services

No comments: