11package io .github .delirius325 .jmeter .backendlistener .elasticsearch ;
22
3+ import org .apache .http .Header ;
34import org .apache .http .HttpEntity ;
45import org .apache .http .HttpStatus ;
56import org .apache .http .entity .ContentType ;
7+ import org .apache .http .message .BasicHeader ;
68import org .apache .http .nio .entity .NStringEntity ;
79import org .elasticsearch .client .Response ;
810import org .elasticsearch .client .RestClient ;
@@ -19,11 +21,17 @@ public class ElasticSearchMetricSender {
1921 private RestClient client ;
2022 private String esIndex ;
2123 private List <String > metricList ;
24+ private String authUser ;
25+ private String authPwd ;
26+ private BasicHeader authHeader ;
2227
23- public ElasticSearchMetricSender (RestClient cli , String index ) {
28+ public ElasticSearchMetricSender (RestClient cli , String index , String user , String pwd ) {
2429 this .client = cli ;
2530 this .esIndex = index ;
2631 this .metricList = new LinkedList <String >();
32+ this .authUser = user .trim ();
33+ this .authPwd = pwd .trim ();
34+ this .authHeader = null ;
2735 }
2836
2937 /**
@@ -76,7 +84,16 @@ public void sendRequest() {
7684
7785 HttpEntity entity = new NStringEntity (bulkRequestBody .toString (), ContentType .APPLICATION_JSON );
7886 try {
79- Response response = this .client .performRequest ("POST" , "/" + this .esIndex +"/SampleResult/_bulk" , Collections .emptyMap (), entity );
87+ if (!this .authUser .equals ("" ) && !this .authPwd .equals ("" )) {
88+ String encodedCredentials = Base64 .getEncoder ().encodeToString ((this .authUser + ":" + this .authPwd ).getBytes ());
89+
90+ this .authHeader = new BasicHeader ("Authorization" , "Basic " + encodedCredentials );
91+ }
92+
93+ Response response = (this .authHeader != null )
94+ ? this .client .performRequest ("POST" , "/" + this .esIndex +"/SampleResult/_bulk" , Collections .emptyMap (), entity , this .authHeader )
95+ : this .client .performRequest ("POST" , "/" + this .esIndex +"/SampleResult/_bulk" , Collections .emptyMap (), entity );
96+
8097 if (response .getStatusLine ().getStatusCode () != HttpStatus .SC_OK ) {
8198 if (logger .isErrorEnabled ()) {
8299 logger .error ("ElasticSearch Backend Listener failed to write results for index {}" , this .esIndex );
0 commit comments